Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Common coding mistake in Python

how to check particular char of string in list available or not

invalid syntax mistake

for char in original_string
    if char in characters_to_remove:
Enter fullscreen mode Exit fullscreen mode

Image description

solution
put colon after for
Note put colon after for ,def ,if,else
Note remember the indention of for,if,else and pass
indention of for and if

for char in original_string:
    if char in characters_to_remove:
Enter fullscreen mode Exit fullscreen mode

indention for,if and data

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
Enter fullscreen mode Exit fullscreen mode

Indention between for,if and local print global print

even = []

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
        print(newdata)
print(even)
Enter fullscreen mode Exit fullscreen mode

indention between for,if,else,print

for max_data in words_list:
    if maxdatas>max_data:
       maxdatas=maxdatas
    else:
         maxdatas=max_data
print(maxdatas)
Enter fullscreen mode Exit fullscreen mode

indention between for,if,else,pass,print

for max_data in words_list:
    if maxdatas>max_data:
       pass
    else:
         pass
print(maxdatas)
Enter fullscreen mode Exit fullscreen mode

IndentationError: expected an indented block
Indention error b/w double for block

data = (4,6,9,10)
list=[]

for char in data:
    if char%2==0:
       list.append(char)

    for lits in list:

    print("Original String:", lits)
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = (4, 6, 9, 10)
my_list = []

for number in data:
    if number % 2 == 0:
        my_list.append(number)

for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

wrong

def add():
    data="python"
    my=["o","n"]
    new=[]
    for newdata in data
    if my in newdata
Enter fullscreen mode Exit fullscreen mode

Correct
always iterate in string,list,dictionary,tuple not single variable of list

if newdata in my
Enter fullscreen mode Exit fullscreen mode
def add():
    data="python"
    my=["o","n"]
    new=[]
    for newdata in data
    if newdata in my
Enter fullscreen mode Exit fullscreen mode

How to add new char in empty string or exisiting string without for loop

empty_string = ""  # An empty string

new_char1 = "Hello, "
new_char2 = "world!"

# Concatenating strings
new_string = empty_string + new_char1 + new_char2

# Using the += operator
empty_string += new_char1
empty_string += new_char2

print("Empty String:", empty_string)
print("New String after adding characters:", new_string)
Enter fullscreen mode Exit fullscreen mode

How to add new char in empty string or exisiting string inside for loop

data = "python"
vowels = "aeiou"
mynew = ""

for char in data:
    if char not in vowels:
        mynew += char
Enter fullscreen mode Exit fullscreen mode

print in new line or in list observe

data = [4, 16, 9, 20]

even = []

for newdata in data:
    if newdata%2 == 0:
        print(newdata)
Enter fullscreen mode Exit fullscreen mode

output

Image description

data = [4, 16, 9, 20]

even = []

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
print(even)  
Enter fullscreen mode Exit fullscreen mode

output

Image description

wrong
dont put gap b/w + and = operator

data="python"  
vowel=["a","i","o","e","u"]
mynew=""
for mydata in data:
    if mydata not in vowel:
       mynew + = mydata
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data="python"  
vowel=["a","i","o","e","u"]
mynew=""
for mydata in data:
    if mydata not in vowel:
       mynew += mydata
Enter fullscreen mode Exit fullscreen mode
data = (4, 6, 9, 10)
my_list = []

for number in data:
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

wrong:

data = (4, 6, 9, 10)
my_list = []

for number in range(len(data)):
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

Solution
iterate over the indices and then access the elements whenever you use range

data = (4, 6, 9, 10)
my_list = []

for index in range(len(data)):
    if data[index] % 2 == 0:
        my_list.append(data[index])

print("Original List of Even Numbers:", my_list)

for item in my_list:
    print("Even Number:", item)
Enter fullscreen mode Exit fullscreen mode

wrong

data={"name":"rakesh","age":33}
name=data[name]
print(name)
Enter fullscreen mode Exit fullscreen mode

Image description

correct
whenever string is in dictionary to access its value use double quotes

data={"name":"rakesh","age":33}
name=data["name"]
print(name)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[elementname for data in list if 5==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[data for data in list if element==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

correct

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[data for data in list if 5==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key value)
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key, value)
Enter fullscreen mode Exit fullscreen mode
data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key, ":", value)
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=null
for key, value in data.items():
    cost +=value
print(cost)
Enter fullscreen mode Exit fullscreen mode

Image description

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=""
for key, value in data.items():
    cost +=value
print(cost) 
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
for key, value in data.items():
    cost +=value
print(cost) 
Enter fullscreen mode Exit fullscreen mode

wrong
RuntimeError: dictionary changed size during iteration

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
for key, value in data.items():
   data["guava"]=40
print(cost) 
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
update={}
for key, value in data.items():
   update["guava"]=40
   cost +=value
data.update(update)   
print(data,":",cost)
Enter fullscreen mode Exit fullscreen mode

Declaration of empty datatype to create or append to create new

dict={}   // dict[char] +=number  or  dict[char] ="word
list=[]  //list.append(data)
string=""  // create new string mynew + = mydata
number=0   // create new string dict[char]+ = number
result_even = {'even': []}//{"group1": [1, 2, 3]}
result_dict = {'odd': {}, 'even': {}}
 result_dict[key] = []
Enter fullscreen mode Exit fullscreen mode

image

Image description

==========================================================

Image description

==========================================

Image description

===============================================

Image description

TIPS

any data type dictionary,set,tuple convert in list using list comprhension then whatever fun u r applying in list u can apply in list comprhension below sum and len fun is applying on list comprhension

Image description

Wrong
how to search particular value based on key

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search=""
for key,value in contacts_dict.items():
    if contacts_dict[key]==name_to_lookup:
       search=contacts_dict[value]
print(search)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

Correct

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "charlie@example.com"
search=""
for key,value in contacts_dict.items():
    if contacts_dict[key]==name_to_lookup:
       search=contacts_dict[key]
print(search)
Enter fullscreen mode Exit fullscreen mode

output

charlie@example.com

grouped_dict = {
    "group1": [1, 2, 7, 3],
    "group2": [4, 5, 5, 6],
    "group3": [7, 8, 9, 8]
}

target_value = 5

locations = [index for group, elements in grouped_dict.items() for index, value in enumerate(elements) if value == target_value]

if locations:
    print(f"The value {target_value} is located in the following places:")
    for location in locations:
        print(f"Group '{location[0]}' at index {location[1]}")
else:
    print(f"The value {target_value} is not found in the dictionary.")
Enter fullscreen mode Exit fullscreen mode

Correct

grouped_dict = {
    "group1": [1, 2, 7, 3],
    "group2": [4, 5, 5, 6],
    "group3": [7, 8, 9, 8]
}

target_value = 5

locations = [(group, index) for group, elements in grouped_dict.items() for index, value in enumerate(elements) if value == target_value]

if locations:
    print(f"The value {target_value} is located in the following places:")
    for location in locations:
        print(f"Group '{location[0]}' at index {location[1]}")
else:
    print(f"The value {target_value} is not found in the dictionary.")
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

Image description
dict_item[word]=data

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=data
    else:   
       dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

correct

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=[data]
    else:   
       dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

=========or==========

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=[]

    dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search = ""
for data in contacts_dict:
    if contacts_dict[data] == name_to_lookup:
        search = contacts_dict[data]
print(search)
Enter fullscreen mode Exit fullscreen mode

Correct

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search = ""

for key, value in contacts_dict.items():
    if key == name_to_lookup:
        search = value

print(search)
Enter fullscreen mode Exit fullscreen mode

output

bob@example.com
Enter fullscreen mode Exit fullscreen mode

two ways to find sum of value in list

my_list = [8, 9, 7, 9, 56]
sum=0
for data in my_list:
    sum +=data
print(sum)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_list = [8, 9, 7, 9, 56]
new_sum = sum(my_list)
Enter fullscreen mode Exit fullscreen mode

two way to access if dictionary contain only keys

data = {"name", "age"}

for news in data:
    print(news)
Enter fullscreen mode Exit fullscreen mode

Image description

data = {"name", "age"}

# Convert the set to a list
data_list = list(data)

# Access the first element
first_element = data_list[0]

print(first_element)
Enter fullscreen mode Exit fullscreen mode

output

Image description

wrong

data = {"name", "age"}
name=data["name"]
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
name=data[1]
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
for keys in data.keys():
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
for keys in data.items():
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):

        print(my_list[index])
Enter fullscreen mode Exit fullscreen mode

correct

input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):
        if index < len(my_list): 
         print(my_list[index])
Enter fullscreen mode Exit fullscreen mode
input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):
        my_list_char = my_list[index % len(my_list)]
        print(my_list_char)
Enter fullscreen mode Exit fullscreen mode

wrong

two ways to find sum of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90

sum_of_values = 0
for value in data.values():
    sum_of_values += value

print(sum_of_values)
Enter fullscreen mode Exit fullscreen mode

2nd way

sum(data.values())
Enter fullscreen mode Exit fullscreen mode

two ways to find length of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
len=0
sum_of_values = 0
for key in data.keys():
    len += 1
print(len)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}
dict_length = len(my_dict)
Enter fullscreen mode Exit fullscreen mode

3 ways to find avg of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
len=0
sum_of_values = 0
avg=0
for key,values in data.items():
    len += 1
    sum_of_values +=values
avg=sum_of_values/len  
print(avg)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}

total = 0
count = 0

for value in my_dict.values():
    total += value
    count += 1

if count > 0:
    average = total / count
    print("Average value:", average)
else:
    print("The dictionary is empty.")
Enter fullscreen mode Exit fullscreen mode

3rd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}

if len(my_dict) > 0:
    average = sum(my_dict.values()) / len(my_dict)
    print("Average value:", average)
else:
    print("The dictionary is empty.")
Enter fullscreen mode Exit fullscreen mode
# Online Python - IDE, Editor, Compiler, Interpreter
listing={"apple":80,"banana":20,"peru":35,"mango":28}
dict_item={}
length=0
sums=0
avg=0
for index in range(len(listing.keys())):
    pass

avg=sum(listing.values())/(index+1) 
print(avg)
Enter fullscreen mode Exit fullscreen mode

find avg of all values if dictionary using list comprehension

# Online Python - IDE, Editor, Compiler, Interpreter
listing={"apple":80,"banana":20,"peru":35,"mango":28}
dict_item={}
length=0
sums=0
avg=0
listsum=[value for key,value in listing.items()]
print(listsum) 
listlen=[1 for key in listing.keys()]
print(listlen) 
sums=sum(listsum)
print(sums) 
length=len(listlen)
print(length) 
avg=sums/length
print(avg) 
Enter fullscreen mode Exit fullscreen mode

output

Image description

** 2 ways max data**

words_list = [20,60,70,80]
maxdatas=0
for max_data in words_list:
    if maxdatas>max_data:
       maxdatas=maxdatas
    else:
         maxdatas=max_data
print(maxdatas)  
Enter fullscreen mode Exit fullscreen mode
max(list)
Enter fullscreen mode Exit fullscreen mode

how to find index of particular value of list

list[3]
Enter fullscreen mode Exit fullscreen mode
listing = [6, 9, 6, 0, 45, 8]
data = ["good is located in " + str(index) if value == 8 else "bad" for index, value in enumerate(listing)]
print(data)
Enter fullscreen mode Exit fullscreen mode

Image description

Cheatsheet

data.update(update)//update specfic value in dictionary
Dict['Emp_ages'] = 20 //add new value in dictionary
for key in data.keys(): or for group in data.keys(): //print all key in dictionary
for value in data.values()://print all value in dictionary
for key,value in data.items(): or for group,ein data.items(): // print both
if char in characters_to_remove: // for list
if char not in characters_to_remove: // for list
if char not in vowels// for string
if length in word_length_dict: // for dictionary
empty_string += new_char1

for index in range(len(data))://iterating with only index in range
    if data[index] % 2 == 0:
Enter fullscreen mode Exit fullscreen mode

original_string = original_string.replace(char, "")
for index, char in enumerate(input_string): // map char to corresponding list
for char, item in zip(input_string, my_list):

for char, item in character_count.items():
    print(f"Character '{char}' is for {item}.")
Enter fullscreen mode Exit fullscreen mode

character_count[char] +=1

length = len(word)

word_length_dict[length] = [word]

word_length_dict[length].append(word)

dict(sorted(my_dict.items(), key=lambda item: item[1]))

sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(1)))

max_value = max(my_dict.values())

average_value = sum(my_dict.values()) / len(my_dict)
del contact_dict[key_to_remove]

contact_email = contacts_dict.get(name_to_lookup, "Contact not found")
print("Task 10 - Email for '{}':", contact_email)
Enter fullscreen mode Exit fullscreen mode
my_list = [8, 9, 7, 9, 56]
new_sum = sum(my_list)
Enter fullscreen mode Exit fullscreen mode
my_list = [8, 9, 7, 9, 56]
len= len(my_list)
Enter fullscreen mode Exit fullscreen mode

my_list = my_list + [new_data] // add new data in list

my_list = [1, 2, 3, 4, 5] // add new data in list
new_data = 6
my_list.append(new_data)
Enter fullscreen mode Exit fullscreen mode

dict["mango"]=90 // add new key value pair in dictionary

new_movie = {"director": "Director3", "genre": "Genre3"}
movies_dict["Movie3"] = new_movie  // add new key value pair in dictionary
Enter fullscreen mode Exit fullscreen mode

if seconlargestd < newdata < maxdata //second largest

merged_dict = {**dict1, **dict2, **dict3}

top_rated_songs = [title for title, rating in song_ratings.items() if rating == 5]

merged_list = list(set(list1 + list2))

strings_list = ["Hello", "World", "!"] // u can join particular string based on condition while iterating in loop
concatenated_string = ' '.join(strings_list)

full_urls = ['https://www.icc-cricket.com' + url for url in url_list] //how to concatenate

my_list.insert(index_to_insert, value_to_add)
my_list.insert(3, value_to_add)
Enter fullscreen mode Exit fullscreen mode

for index, text in enumerate(list): //Find Particular element index

subset = my_list[::2] // print even no

reversed_list = my_list[::-1]

subset = my_list[:3] # Get elements at index 0, 1, and 2 ([1, 2, 3])
subset = my_list[2:] # Get elements from index 2 to the end ([3, 4, 5])

subset = my_list[1:4] # Get elements at index 1, 2, and 3 ([2, 3, 4])

key_list = list(data.keys())

for key in data.keys():
    list.append(key)
Enter fullscreen mode Exit fullscreen mode

value_list = list(data.values())

for value in data.values():
    list.append(value)
Enter fullscreen mode Exit fullscreen mode

index = my_list.index(value_to_find) // how to find index of list

Summary

put colon not semicolon after for ,def ,if,else
after print or declaration of variable not put semicolon
indention of for and if
indention of if and else
indention for,if and data or print
Indention between for,if and local print global print
indention between for,if,else,print
indention between for,if,else,pass,print
always iterate in string,list,dictionary,tuple not single variable of list
How to add new char in empty string or exisiting string
print in new line or in list observe
How to add new char in empty string or exisiting string without for loop or inside for loop
Indention error b/w double for block
dont put gap b/w + and = operator
iterate over the indices and then access the elements whenever you use range
whenever string is in dictionary to access its value use double quotes
print key and value by comma or colon
not concatenate string with integer while doing calculation of sum of all dictionary value
RuntimeError: dictionary changed size during iteration
Declaration of empty datatype to create or append to create new like list,dictionary,string,integer,list of dictionary,dictionary of dictionary
Mapping char to corresponding item in list using zip
difference between char_count[item]=char or char_count[item]=[char] and word_count[length].append(word) inside for loop
how to search particular value based on key
two ways to find sum,length of value in list
3 ways to find avg of value in list
two way to access if dictionary contain only keys
two ways to find sum,len of dictionary
3ways to find avg of dictionary
2 ways to find max data in list
find second largest data
how to convert string to list

QUESTION

how to access list value or string value using index
how to access value from list of dictionary
difference between enumerate and zip method
.How to add new char in empty string or existing string
.How to Mapping char to corresponding item in list and dictionary OR how to convert list to dictionary
how to convert dictionary to list
how to search particular value based on key
how to find second largest data
how to convert dictionary keys or value in list
how to combine two list
how to reverse list
how to get specific range of element from list
how to get last 3 element of list
how to get skip fist element from list
how to combine dictionary
how to concatenate string in each element of list
how to update specific value in dictionary
how to find index of particular value of list or string
how to iterate index of list
how to string to list
Solution

my_list[index]

synonyms = {"quick": ["fast", "swift", "speedy"]}
list(synonyms.keys())

zip method iterates over element pairs and contain two parameter argument while enumerate iterates over element and index and contain one parameter argument of list

empty_string += new_char1

using enumerate or zip
using list comrehension or append while iterating dictionary

movies_dict["Movie3"]

if seconlargestd < newdata < maxdata //second largest

key_list = list(data.keys()) or list.append(key) inside for loop

merged_list = list(set(list1 + list2)) or listnew=list1 + list2

reversed_list = my_list[::-1]

subset = my_list[1:4]

subset = my_list[:3]

subset = my_list[1:]

merged_dict = {**dict1, **dict2, **dict3}

full_urls = ['https://www.icc-cricket.com' + url for url in url_list]

data.update(update)

list[3] or [data for data in list if 5==data] or using enumerte

for index, char in enumerate(input_string):
     character_count[char] = my_list[index]
#printing
for index, char in enumerate(input_string):
     my_list_char = my_list[index % len(my_list)]
     print(my_list[index])
Enter fullscreen mode Exit fullscreen mode

data= ["good is located in " + str(index) if value == 8 else "bad" for index, value in enumerate(listing)]
using enumerate
list(string) or append inside for loop

Top comments (0)