201 Python Programming Exercises For All
201 Python Programming Exercises For All
Edcorner Learning
Table of Contents
Introduction
Module 1 Tuples
Module 2 Dictionaries
Module 3 Data type
Module 4 Conditionals
Module 5 Loops
Module 6 Exceptions
Module 7 Functions
Module 8 Regular Expressions
Module 9 Classes
Module 10 Strings
Module 11 Dictionary
Module 12 Lists
Introduction
my_range =
print(list(my_range)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Given the code below, use the correct argument(s) for the range() function
on line 1 in order to return a range of consecutive integers from 0 to 9
inclusively. Use two arguments inside the parentheses of range()!
my_range =
print(list(my_range)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3. Given the code below, use the correct argument(s) for the range() function
on line 1 in order to return a range of consecutive integers from 117 to 129
exclusively.
my_range =
print(list(my_range)) #[117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128]
4. Given the code below, use the correct argument(s) for the range() function on
line 1 in order to return [10,13,16,19] when converted to a list.
my_range =
my_range =
print(list(my_range)) #[-10]
Module 2 Dictionaries
9. Given the code below, use the correct code on line 3 in order to return
the value associated with key 4. Do not use a method as a solution for this
exercise!
value =
print(value)
11. Given the code below, use the correct code on line 3 in order
to update the value associated with key 4 to "Cardano".
print(crypto[4])
12. Given the code below, use the correct code on line 3 in order to
add a new key-value pair to the dictionary: 6: "Monero"
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:
"XRP"}
print(crypto[6])
13. Given the code below, use the correct code on line 3 to return
the number of key-value pairs in the dictionary.
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar",
5: "XRP"}
number =
print(number)
14. Given the code below, use the correct code on line 3 to delete the
key-value pair associated with key 3. Do not use a method as a
solution for this exercise!
print(crypto)
15. Given the code below, use the correct code on line 3 in order
to delete the key-value pair associated with key 3. This time,
use a method as a solution for this exercise!
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar",
5: "XRP"}
print(crypto)
16. Given the code below, use the correct code on line 3 in order to
verify that 7 is not a key in the dictionary.
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:
"XRP"}
check =
print(check)
`17. Given the code below, use the correct method on line 3 in order
to delete all the elements in the dictionary.
crypto.
print(crypto)
18. Given the code below, use the correct code on line 3 in order to
get a list of tuples, where each tuple represents a key-value pair in the
dictionary.
result =
print(list(result))
19. Given the code below, use the correct function on line 3 in
order to get the sum of all the keys in the dictionary.
add =
print(add)
20. Given the code below, use the correct method on line 3 in order to
get a list of all the values in the dictionary.
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:
"XRP"}
val =
print(list(val))
21. Given the code below, use the correct function on line 3 in
order to get the smallest key in the dictionary.
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar",
5: "XRP"}
key =
print(key)
22. Given the code below, use the correct method on line 3 in order to
get a list of all the keys in the dictionary.
crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:
"XRP"}
keys =
print(list(keys))
23. Given the code below, use the correct method on line 3 in
order to return and remove an arbitrary key-value pair from the
dictionary.
conv =
print(type(conv))
25. Given the code below, use the correct function on line 3 in
order to convert value to an integer.
value = "10"
conv =
print(type(conv))
26. Given the code below, use the correct function on line 3 in order
to convert value to a floating-point number.
value = 10
conv =
print(type(conv))
27. Given the code below, use the correct function on line 3 in
order to convert value to a list.
value = "Hello!"
conv =
print(type(conv))
28. Given the code below, use the correct function on line 3 in order
to convert value to a tuple.
conv =
print(type(conv))
30. Given the code below, use the correct function on line 3 in order
to convert value to a binary representation.
value = 10
conv =
print(conv)
31. Given the code below, use the correct function on line 3 in
order to convert value to a hexadecimal representation.
value = 10
conv =
print(conv)
32. Given the code below, use the correct function on line 3 in order
to convert value from binary to decimal notation.
value = '0b1010'
conv =
print(conv)
33. Given the code below, use the correct function on line 3 in
order to convert value from hexadecimal to decimal notation.
value = '0xa'
conv =
print(conv)
Module 4 Conditionals
34. Considering the code below, write code that prints out True! if x has 50
characters or more.
x = "The days of Python 2 are almost over. Python 3 is the king now."
35. Considering the code below, write code that prints out True!
if x is a string and the first character in the string is T.
x=0
66. Write a while loop that prints out the value of x plus 10 while x is
less than or equal to 15 and the remainder of x divided by 5 is 0. Be
careful not to end up with an infinite loop!
x = 10
67. Write a while loop that prints out the absolute value of x
while x is negative. Be careful not to end up with an infinite
loop!
x = -7
68. Write a while loop that prints out the value of x times y while x is
greater than or equal to 5 and less than 10, and prints out the result of
x divided by y when x becomes 10. Be careful not to end up with an
infinite loop!
x=5
y=2
69. Write code that will iterate over the x list and multiply by 10 only the
elements that are greater than 20 and print them out to the screen.
Hint: use nesting!
x = [2, 4, 6, 8]
y = [5, 10, 15, 20]
73. Write code that will iterate over the x and y lists and
multiply each element of x with each element of y that is less
than or equal to 10, also printing the results to the screen. For ys
elements that are greater than 10, multiply each element of x
with y squared.
Hint: use nesting!
x = [2, 4, 6, 8]
y = [5, 10, 15, 20]
74. Write code that will print out each character in x doubled if that
character is also inside y. Hint: use nesting!
x = "cryptocurrency"
y = "blockchain"
75. Write code that will iterate over the range generated by
range(9) and for each element that is between 3 and 7
inclusively print out the result of multiplying that element by the
second element in the same range.
Hint: use nesting!
my_range = range(9)
76. Write code that will iterate over the range starting at 1, up to but
not including 11, with a step of 2, and for each element that is
between 3 and 8 inclusively print out the result of multiplying that
element by the last element in the same range. For any other element
of the range (outside [3-8]) print Outside!
Hint: use nesting!
77. Write code that will iterate over the range starting at
5, up to but not including 25, with a step of 5, and for each
element that is between 10 and 21 inclusively print out the result
of multiplying that element by the second to last element of the
same range. For any other element of the range (outside [10-21])
print Outside! Finally, after the entire range is exhausted print
out The end!
Hint: use nesting!
78. Write a while loop that prints out the value of x times 11 while x
is less than or equal to 11. When x becomes equal to 10, print out x is
10! Be careful not to end up with an infinite loop!
x=5
79. Insert a break statement where necessary in order to
obtain the following result:
1
1
100
20
10
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(i * j)
print(i)
print(j)
80. Insert a break statement where necessary in order to
obtain the following result:
1
1
100
20
10
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(i * j)
print(i)
print(j)
81. Insert a break statement where necessary in order to
obtain the following result:
1
1
100
10
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(i * j)
print(i)
print(j)
82. Insert a continue statement where necessary in order to
obtain the following result:
1
1
100
20
200
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(i * j)
print(i)
print(j)
83. Insert a continue statement where necessary in order to
obtain the following result:
1
1
100
100
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(i * j)
print(i)
print(j)
Module 6 Exceptions
84. Fix the code below so that it doesn't generate a SyntaxError. Hint! The
result should be 20 200
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0
print(i * j)
85. Fix the code below so that it doesn't generate a TypeError. Hint!
The result should be 20 200
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if y % 2 == 0:
print(i * j)
86. Fix the code below so that it doesn't generate an
IndexError. Hint! The result should be 200 200
x = [1, 2]
y = [10, 100]
for i in x:
for j in y:
if i % 2 == 0:
print(x[1] * y[2])
87. Add the necessary clause(s) to the code below so that in case the
ZeroDivisionError exception is raised then the program prints out
Zero! to the screen.
try:
print(25 % 0)
88. Add the necessary clause(s) to the code below so that in case
the code under try raises no exceptions then the program prints
out the result of the math operation and the string Clean! to the
screen.
try:
print(25 % 5 ** 5 + 5)
except:
print("Bug!")
89. Add the necessary clause(s) to the code below so that no matter if
the code under try raises any exceptions or not, then the program
prints out the string Result! to the screen.
try:
print(25 % 0 ** 5 + 5)
except:
print("Bug!")
90. Add the necessary clause(s) to the code below so that in
case the code under try raises the ZeroDivisionError exception
then the program prints out the string Zero! to the screen;
additionally, if the code under try raises the IndexError
exception then the program prints out the string Index! to the
screen.
result = my_func(3,3,3)
print(result)
98. Implement a function called my_func() that takes a single
parameter x and multiplies it with each element of range(5), also
adding each multiplication result to a new (initially empty) list called
my_new_list. Finally, the list should be printed out to the screen after
the function is called.
result = my_func(2)
print(result)
99. Implement a function called my_func() that takes a single
parameter x (a string) and turns each character of the string to
uppercase, also returning the result when the function is called
result = my_func([11, 12, 13, 11, 15, 18, 18, 22, 20, 16, 12])
print(result)
101. Implement a function called my_func() that takes a single
parameter x (a tuple) and for each element of the tuple that is
greater than 4 it raises that element to the power of 2, also
adding it to a new (initially empty) list called my.newlist. Finally,
the code returns the result when the function is called.
result = my_func((2, 3, 5, 6, 4, 8, 9))
print(result)
102. Implement a function called my_func() that takes a single
parameter x (a dictionary) and multiplies the number of elements in
the dictionary with the largest key in the dictionary, also returning the
result when the function is called.
result = my_func(5)
print(result)
104. Implement a function called my_func() that takes a single
positional parameter x and two default parameters y and z which are
equal to 100 and 200 respectively, and adds them together, also
returning the result when the function is called.
result = my_func(50)
print(result)
105. Implement a function called my_func() that takes two
default parameters x (a list) and y (an integer), and returns the
element in x positioned at index y, also printing the result to the
screen when called.
result = my_func(list(range(2,25,2)), 4)
print(result) #result should be 10
106. Implement a function called my_func() that takes a positional
parameter x and a variable-length tuple of parameters and returns the
result of multiplying x with the second element in the tuple, also
returning the result when the function is called.
var = 10
def my_func(x):
my_func(20)
109. Add the correct line(s) of code inside the function in order to
get 100 as a result of calling myfunc() and have the result printed
out to the screen.
var = 10
def my_func(x):
print(x * var)
my_func(20)
110. Make the necessary adjustment inside the function in order to get
120 as a result of calling myfunc() and have the result printed out to
the screen.
def my_func(x):
print(x * var)
var = 12
my_func(10)
111. Add the necessary line of code inside the function in
order to get 80 as a result of calling myfunc() and have the result
printed out to the screen.
var = 8
def my_func(x):
print(x * var)
var = 12
my_func(10)
112. Write code that will import only the pi variable from the math
module and then it will format it in order to have only 4 digits after
the floating point. Of course, print out the result to the screen using
the print() function.
113. Add the necessary code in between print's parentheses in
order to read the content of test.txt as a string and have the
result printed out to the screen.
f = open("test.txt", "r")
print()
Solution:
f = open("test.txt", "r")
print(f.read())
114. Add the necessary code in between print's
parentheses in order to read the content of test.txt as a list where
each element of the list is a row in the file, and have the result
printed out to the screen.
f = open("test.txt", "r")
print()
Solution:
f = open("test.txt", "r")
print(f.readlines())
115. Add the necessary code on line 5 in order to bring back the
cursor at the very beginning of test.txt before reading from the file
once again.
f = open("test.txt", "r")
f.read()
print(f.read())
Solution:
f = open("test.txt", "r")
f.read()
f.seek(0)
print(f.read())
116. Add the necessary code on line 5 (in between the parentheses
of print()) in order to get the current position of the cursor inside
test.txt and have the result printed out to the screen.
f = open("test.txt", "r")
f.read(5)
print()
Solution:
f = open("test.txt", "r")
f.read(5)
print(f.tell())
117. Add the necessary code on line 5 (in between the parentheses of
print()) in order to get the current mode in which test.txt is open
(read, write etc.) and have the result printed out to the screen.
f = open("test.txt", "r")
f.read(5)
print()
Solution:
f = open("test.txt", "r")
f.read(5)
print(f.mode)
118. Add the necessary file access mode on line 1 in order to open
test.txt for appending and reading at the same time.
f = open("test.txt", )
print(f.mode)
Solution:
f = open("test.txt", "a+")
print(f.mode)
119. Add the necessary code on lines 3 and 4 in order to write the
string python to test.txt and have the result of reading the file printed
out to the screen.
f = open("test.txt", "w")
f = open("test.txt", "r")
print(f.read())
Solution:
f = open("test.txt", "w")
f.write("python")
f.close()
f = open("test.txt", "r")
print(f.read())
120. Add the necessary code on lines 3 and 4 in order to write a
list of strings ['python', ' ', 'and', ' 'java'] to test.txt and have the
result of reading the file printed out to the screen.
f = open("test.txt", "w")
f = open("test.txt", "r")
print(f.read())
Solution:
f = open("test.txt", "w")
f.writelines(['python', ' ', 'and', ' ', 'java'])
f.close()
f = open("test.txt", "r")
print(f.read())
121. Add the necessary code starting at line 1 in order to write the
string python and also close test.txt properly using the with statement.
f = open("test.txt", "r")
print(f.read())
Solution :
with open("test.txt", "w") as f:
f.write("python")
f = open("test.txt", "r")
print(f.read())
122. Add the necessary code on lines 4 and 5 in order to delete
the entire content of test.txt.
with open("test.txt", "w") as f:
f.write("python")
f = open("test.txt", "r")
print(f.read())
Solution:
with open("test.txt", "w") as f:
f.write("python")
f = open("test.txt", "r+")
f.truncate()
f = open("test.txt", "r")
print(f.read())
Module 8 Regular Expressions
123. Write code on line 5 in order to match the word Python at the
beginning of the string using the match() method.
import re
result =
print(result.group())
124. Write code on line 5 in order to match the word Bitcoin at the
beginning of the string using the match() method and ignoring the
case. This way, no matter if you have bitcoin or Bitcoin, the match is
done either way.
import re
s = "Bitcoin was born on Jan 3rd 2009 as an alternative to the failure
of the current financial system. In 2017, the price of 1 BTC reached
$20000, with a market cap of over $300B."
print(result.group())
125. Write code on line 5 in order to match the words
Bitcoin was at the beginning of the string using the match()
method. Use the dot (.) belonging to regex syntax in your
solution.
import re
s = "Bitcoin was born on Jan 3rd 2009 as an alternative to the
failure of the current financial system. In 2017, the price of 1 BTC
reached $20000, with a market cap of over $300B."
result =
print(result.group())
126. Write code on line 5 in order to match the year 2009 in the string using
the search() method. Use the \d in your solution.
import re
class ClassOne(object):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
class ClassTwo(ClassOne):
def times10(self, x):
return x * 10
class ClassOne(object):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
class ClassTwo(ClassOne):
def times10(self, x):
return x * 10
Module 10 Strings
137. Given the code below, insert the correct negative index on
line 3 in order to get the last character in the string.
my_string = "In 2010, someone paid 10k Bitcoin for two
pizzas."
print(my_string[])
138. Given the code below, insert the correct positive index on line 3
in order to return the comma character from the string.
my_string = "In 2010, someone paid 10k Bitcoin for two pizzas."
print(my_string[])
139. Given the code below, insert the correct negative index on
line 3 in order to return the w character from the string.
print(my_string[])
140. Given the code below, insert the correct method on line 3 in
order to return the index of the B character in the string.
print(my_string.)
141. Given the code below, insert the correct method on line 3 in
order to return the number of occurrences of the letter o in the
string.
print(my_string.)
142. Given the code below, insert the correct method on line 3 in
order to convert all letters in the string to uppercase.
my_string = "In 2010, someone paid 10k Bitcoin for two
pizzas."
print(my_string.)
143. Given the code below, insert the correct method on line 3 in
order to get the index at which the substring Bitcoin starts.
print(my_string.)
Module 11 Dictionary
144. Create the get_name function which returns the value of the key
name
such key does not exist the function should return the string
unknown name .
def get_name(dictionary: dict) -> str:
# TODO
arr = [
{
'name': 'John',
'age': 25
},
{
'age': 20
},
{
'name': 'Tom',
'age': 38
},
{}
]
for dictionary in arr:
print(get_name(dictionary))
145. Create the get_name function which returns the value of the key
name
such key does not exist the function should return the string
unknown name .
def get_name(dictionary: dict) -> str:
# TODO
arr = [
{
'name': 'John',
'age': 25
},
{
'age': 20
},
{
'name': 'Tom',
'age': 38
},
{}
]
for dictionary in arr:
print(get_name(dictionary))
146. Sort the arr list of dictionaries by a value in the age key. Sorted
list save in the sorted_arr variable.
Expected result:
[{'name': 'Alice', 'age': 20}, {'name': 'lohn', 'age': 25}, {'name':
'Tom', 'age': 38}]
arr = [
{
'name': 'John',
'age': 25
},
{
'name': 'Alice',
'age': 20
},
{
'name': 'Tom',
'age': 38
}
]
sorted_arr =
Solution:
arr = [
{
'name': 'John',
'age': 25
},
{
'name': 'Alice',
'age': 20
},
{
'name': 'Tom',
'age': 38
}
]
sorted_arr = sorted(arr, key=lambda key:
key['age'])
147. Convert two lists into the dictionary. The keys list stores the
keys of the dictionary, and the values list stores their values.
Expected result:
{'name': 'john', 'age': 25,'grade': 'B'}
dictionary =
Solution:
keys = ['name', 'age', 'grade']
values = ['John', 25, 'B']
dictionary = {
'name': 'John',
'age': 25,
'grade': 'B',
}
arr =
Solution:
dictionary = {
'name': 'John',
'age': 25,
'grade': 'B',
}
arr = list(dictionary.keys())
149. Merge two dictionaries: dict_1 and dict_2. Save the result in the
new_dict dictionary.
Expected result:
{'name': 'Anna', 'age': 20, 'weight': 55, 'height': 170}
new_dict =
Solution:
dict_1 = {'name': 'Anna', 'age': 20}
dict_2 = {'weight': 55, 'height': 170}
# Python 3.9+
# new_dict = dict_1 | dict_2
150. Sort the dictionary by the key in ascending order.
Expected result:
{'Alice': 10, 'Anna': 20, 'Clinton': 18, 'Mark': 15}
dictionary['name'] = 'Mark'
152. Convert the dictionary into a list of tuples. The first element of
tuples should be a dictionary key and the second one a dictionary
value. Save the result in the arr_of_tupies variable.
Expected result:
[('name', 'Anna'), ('age', 20), ('weight', 55), ('height', 170)]
arr_of_dicts = [
{
'name': 'John',
'age': 25
},
{
'color': 'blue'
},
{
'height': 175,
'weight': 55
}
]
for dictionary in arr_of_dicts:
if key_exists(dictionary):
print(f'"name" key exists in {dictionary}')
else:
print(f'"name" key does not exist in {dictionary}')
154. Remove the name key from the dictionary and save its value-to-
value variable.
Expected result:
'Anna'
dictionary = {'name': 'Anna', 'age': 20, 'weight': 55, 'height':
170}
value =
Solution
dictionary = {'name': 'Anna', 'age': 20, 'weight': 55, 'height':
170}
value = dictionary.pop('name')
155. Create the new_dict dictionary with all elements from the
dictionary except for the age key.
Use diet comprehension.
Expected result:
{'name': 'Anna', 'weight': 55, 'height': 170}
new_dict =
Solutions
dictionary = {'name': 'Anna', 'age': 20, 'weight': 55, 'height': 170}
key =
Solution
dictionary = {'Anna': 20, 'Mark': 15, 'Clinton': 18, 'Alice': 10}
# or
# key = max(dictionary, key=lambda item:
dictionary[item])
157. Get the smallest value from the dictionary. Save the result
in the value variable.
Expected result:
10
dictionary = {'Anna': 20, 'Mark': 15, 'Clinton': 18, 'Alice': 10}
value =
Solution
dictionary = {'Anna': 20, 'Mark': 15, 'Clinton': 18, 'Alice': 10}
value = min(dictionary.values())
158. Get the name with the smallest value in the age key. Save
the result in the value variable.
Expected result:
'Alice'
arr_of_dicts = [
{
'name': 'John',
'age': 26
},
{
'name': 'Anna',
'age': 28
},
{
'name': 'Alice',
'age': 25
}
]
value =
Solution:
arr_of_dicts = [
{
'name': 'John',
'age': 26
},
{
'name': 'Anna',
'age': 28
},
{
'name': 'Alice',
'age': 25
}
]
new_dictionary =
Solution
dictionary = {'name': 'Anna', 'age': 20}
new_dictionary = dictionary.copy()
# or
# new_dictionary = dict(dictionary)
160. Create a copy of the dictionary and save it in the new_dictionary
variable (deep copy).
new_dictionary =
Solution
import copy
new_dictionary = copy.deepcopy(dictionary)
161. Get dictionary values as a list. Save the result in the
names
variable.
Expected result:
['Anna', 'Mark', 'Clinton', 'Alice']
names =
Solution
dictionary = {'Anna': 20, 'Mark': 15, 'Clinton': 18, 'Alice': 10}
names = [*dictionary]
# or
# names = list(dictionary)
162. Invert the dictionary mapping.
Expected result:
{20: 'Anna', 15: 'Mark', 18: 'Clinton', 10: 'Alice'}
dictionary =
Solution
dictionary = {'Anna': 20, 'Mark': 15, 'Clinton': 18, 'Alice': 10}
words =
Solution
sentence = 'I am learning Python. I love Python.
Python is the future!'
words = {}
sentence = sentence.replace('.', '').replace('!', '')
for word in sentence.split():
if word not in words:
words[word] = 0
words[word] += 1
# or
# from collections import Counter
# sentence = sentence.replace('.', '').replace('!', '')
# words = Counter(sentence.split())
164. Merge two dictionaries dict_1 and dict_2. Add values for keys that
appear in both dictionaries. Save the result in the combined_dict
dictionary.
Expected result:
{'a': 6, 'b': 5, 'c': 4}
combined_dict =
Solution
from collections import Counter
dict_1 = {'a': 1, 'b': 2}
dict_2 = {'a': 5, 'b': 3, 'c': 4}
counter_1 = Counter(dict_1)
counter_2 = Counter(dict_2)
combined_dict = counter_1 + counter_2
165. Create the list of dictionaries arr_of_dicts where every
dictionary will have two keys: id and name.
The value for the id key should start with 1 and then it should be
incremented in every
dictionary.
The value for the name key should match with elements in the list
names .
Expected result:
[{'id': 1, 'name': 'Alice'}, {'id': 2, 'name':
{'id': 4, 'name': 'Sara'}]
'Tom'}, {'id': 3, 'name': 'john'}.
names = ['Alice', 'Tom', 'John', 'Sara']
arr_of_dicts =
Solution
names = ['Alice', 'Tom', 'John', 'Sara']
arr_of_dicts = [
{
'id': num,
'name': name
} for num, name in enumerate(names, start=1)
]
166. Create the dictionary where elements of the their value will be
the string Be happy! .
Arr will be stored as keys of dictionary and
Expected result:
{50: 'Be happy!', 51: 'Be happy!', 52: 'Be happy!', 53: 'Be happy!',
54: 'Be happy!'}
dictionary =
Solution
arr = range(50, 55)
arr = [1, 2, 3]
arr =
Solution
arr = [1, 2, 3]
arr[-1] = 0
168. Create the new arr list which contains only last two
elements of the arr list.
Expected result:
[8, 9]
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr =
Solution
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr = arr[-2:]
169. Create the new_arr list which contains only first five elements of the arr
list.
Expected result:
[1, 2, 3, 4, 5]
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr =
Solution
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr = arr[:5]
170. Create the new_arr list which contains only the fourth, fifth and
sixth element of the arr list.
Expected result:
[4, 5, 6]
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr =
Solution
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr = arr[3:6]
171. Create the new arr list which contains only odd elements of
the arr list.
Expected result: [1, 3, 5, 7, 9]
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr =
Solution
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr = arr[::2]
# or
# new_arr = [item for item in arr if item % 2 != 0]
172. Reverse the order of elements in the arr list. Save the
result in the new_arr variable.
Expected result:
[2, 7, 7, 6, 5, 7, 3, 8, 1]
arr = [1, 8, 3, 7, 5, 6, 7, 7, 2]
new_arr =
Solution
arr = [1, 8, 3, 7, 5, 6, 7, 7, 2]
new_arr = arr[::-1]
# or
# new_arr = list(reversed(arr))
173. Create the function is_iist_empty which checks if a provided
to it list is empty. If a list is empty the function should return
True otherwise False.
def is_list_empty(arr: list) -> bool:
# TODO
arrays = [[1, 2, 3], ['item'], []]
for arr in arrays:
if is_list_empty(arr):
print(f'{arr} is a empty list')
else:
print(f'{arr} contains elements')
Solution:
def is_list_empty(arr: list) -> bool:
return not bool(arr)
arrays = [[1, 2, 3], ['item'], []]
for arr in arrays:
if is_list_empty(arr):
print(f'{arr} is a empty list')
else:
print(f'{arr} contains elements')
174. Create the new_arr list which contains elements from two
lists. First there should be elements from the arr i list then
elements from the arr 2 list.
Expected result:
[1, 2, 3, 4, 5]
arr_1 = [1, 2]
arr_2 = [3, 4, 5]
new_arr =
Solution
arr_1 = [1, 2]
arr_2 = [3, 4, 5]
new_arr = arr_1 + arr_2
175. Add all elements from the arr_ _i list to the arr_2 list.
Expected result:
[1, 2, 3, 4]
arr_1 = [3, 4]
arr_2 = [1, 2]
Solution
arr_1 = [3, 4]
arr_2 = [1, 2]
arr_2.extend(arr_1)
176. Create a copy of the am list and save it in the new_arr variable
(shallow copy).
arr = [1, 2]
new_arr =
Solution
arr = [1, 2]
new_arr = arr.copy()
# or
# new_arr = list(arr)
177. Create a copy of the am list and save it in the new_arr
variable (deep copy).
arr = [1, [2]]
new_arr =
Solution
import copy
arr = [1, [2]]
new_arr = copy.deepcopy(arr)
178. Get the number of elements in the arr list. Save the result in
the arr_length variable.
Expected result:
4
arr = [1, 2, 3, 4]
arr_length =
Solution
arr = [1, 2, 3, 4]
arr_length = len(arr)
179. Count the occurrences of the digit 2 in the am list. Save the result
in the count variable.
Expected result:
3
arr = [1, 2, 3, 4, 2, 5, 5, 2]
count =
Solution
arr = [1, 2, 3, 4, 2, 5, 5, 2]
count = arr.count(2)
180. Remove the last element from the arr list and save its result to
the last item variable.
arr = [1, 2, 3]
last_item =
Solution
arr = [1, 2, 3]
last_item = arr.pop()
181. Remove the element with the value 2 from the arr
list.
Expected result:
[1, 3, 4]
arr = [1, 2, 3, 4]
Solution
arr = [1, 2, 3, 4]
arr.pop(1)
182. Sort the elements of the arr list in descending
order.
Expected result:
[9, 6, 4, 2]
arr = [2, 6, 4, 9]
Solution
arr = [2, 6, 4, 9]
arr.sort(reverse=True)
183. Create the new_arr list which contains only unique elements from
the arr list.
Expected result:
[1, 2, 3, 4]
arr = [4, 2, 1, 1, 3, 2, 1, 3, 4, 4, 4, 3]
new_arr =
Solution
arr = [4, 2, 1, 1, 3, 2, 1, 3, 4, 4, 4, 3]
new_arr = list(set(arr))
184. Remove the elements with the value i and 3 from the arr list.
Expected result:
[4, 2, 2, 4, 4, 4]
arr = [4, 2, 1, 1, 3, 2, 1, 3, 4, 4, 4, 3]
arr =
Solution
arr = [4, 2, 1, 1, 3, 2, 1, 3, 4, 4, 4, 3]
# or
# list(filter(bool, arr))
188. Find the smallest number in the am list. Save the result in the
smallest number variable.
Expected result:
-60
arr = [104, -60, 0, 399, -30, -5]
smallest_number =
Solution
arr = [104, -60, 0, 399, -30, -5]
smallest_number = min(arr)
189. Create the are_elements_true function which checks if all
elements of the given list are True . The function should return True
or False.
def are_elements_true(arr: list) -> bool:
# TODO
arrays = [[0, True, 1], [22, True], ['a', 'b', 4]]
for arr in arrays:
if are_elements_true(arr):
print(f'All items in {arr} are "True"')
else:
print(f'Some items in {arr} are "False"')
Solution:
def are_elements_true(arr: list) -> bool:
return all(arr)
arrays = [[0, True, 1], [22, True], ['a', 'b', 4]]
for arr in arrays:
if are_elements_true(arr):
print(f'All items in {arr} are "True"')
else:
print(f'Some items in {arr} are "False"')
190. In the numbers list find all numbers which are greater
than 25 . Save the result in the
new numbers Variable.
Expected result:
[88, 45, 98, 34, 55, 48]
numbers = [88, 45, 4, 7, 98, 34, 21, 18, 14, 55, 48, 1]
new_numbers =
Solution
numbers = [88, 45, 4, 7, 98, 34, 21, 18, 14, 55, 48, 1]
duplicates =
Solution
from collections import Counter
def __repr__(self):
return f'{self.name} - {self.age}'
p1 = Person('Tom', 34)
p2 = Person('Alice', 28)
p3 = Person('John', 37)
arr = [p1, p2, p3]
arr.sort(key=lambda x: x.age, reverse=True)
200. Given 2D array calculate the sum of diagonal elements.
Ex: [[1,8,9],[1 ,5,6],[7,6,9] => sum of 1 + 5 + 9 => 15
201. Exercise 3: Given a Python list of numbers. Turn every item of
a list into its square
Given:
aList = [1, 14, 23, 4, 15, 6, 27]
Solution:
Edcredibly App –
https://play.google.com/store/apps/details?
id=com.edcredibly.courses