This data structures exercise is designed for beginners to understand and practice fundamental data structures in Python. You’ll practice Python List, Set, Dictionary, and Tuple questions.
Data structures are crucial for organizing and holding data. To perform any programming task effectively in Python, a strong grasp of data structures is essential.
Solve this exercise to develop a solid understanding of basic data structures in Python.
This Exercise includes the followings: –
- This exercise includes 10 questions, each with a provided solution.
- The questions cover various methods for manipulating lists, dictionaries, sets, and tuples.
- Use an Online Code Editor to solve the exercises.
Exercise 1: List Creation using two lists
Write a code to create a new list using odd-indexed elements from the first list and even-indexed elements from the second
Given two lists, l1 and l2, write a program to create a third list l3 by picking an odd-index element from the list l1 and even index elements from the list l2.
Given:
l1 = [3, 6, 9, 12, 15, 18, 21]
l2 = [4, 8, 12, 16, 20, 24, 28]Code language: Python (python)
Expected Output:
Element at odd-index positions from list one [6, 12, 18] Element at even-index positions from list two [4, 12, 20, 28] Printing Final third list [6, 12, 18, 4, 12, 20, 28]
Show Hint
Use list slicing
Show Solution
To access a range of items in a list, use the slicing operator :. With this operator, you can specify where to start the slicing, end, and specify the step.
For example, the expression list1[ start : stop : step] returns the portion of the list from index start to index stop, at a step size step.
- for 1st list: Start from the 1st index with step value 2 so it will pick elements present at index 1, 3, 5, and so on
- for 2nd list: Start from the 0th index with step value 2 so it will pick elements present at index 0, 2, 4, and so on
Exercise 2: Remove and add item in a list
Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the list.
Given:
list1 = [54, 44, 27, 79, 91, 41]Code language: Python (python)
Expected Output:
List After removing element at index 4 [34, 54, 67, 89, 43, 94] List after Adding element at index 2 [34, 54, 11, 67, 89, 43, 94] List after Adding element at last [34, 54, 11, 67, 89, 43, 94, 11]
Show Hint
Use the list methods, pop(), insert() and append()
Show Solution
pop(index): Removes and returns the item at the given index from the list.insert(index, item): Add the item at the specified position(index) in the listappend(item): Add item at the end of the list.
Exercise 3: Slice list into 3 equal chunks and reverse each chunk
Given:
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]Code language: Python (python)
Expected Outcome:
Chunk 1 [11, 45, 8] After reversing it [8, 45, 11] Chunk 2 [23, 14, 12] After reversing it [12, 14, 23] Chunk 3 [78, 45, 89] After reversing it [89, 45, 78]
Show Hint
- Divide the length of a list by 3 to get the each chunk size
- Run loop three times and use the
slice()function to get the chunk and reverse it
Show Solution
- Get the length of a list using a
len()function - Divide the length by 3 to get the chunk size
- Run loop three times
- In each iteration, get a chunk using a
slice(start, end, step)function and reverse it using thereversed()function - In each iteration,
startandendvalue will change
Exercise 4: Count the occurrence of each element from a list
Write a program to iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element.
Given:
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]Code language: Python (python)
Expected Output:
Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
Show Solution
Exercise 5: Paired Elements from Two Lists as a Set
Write a code to create a Python set such that it shows the element from both lists in a pair.
Given:
first_list = [2, 3, 4, 5, 6, 7, 8]
second_list = [4, 9, 16, 25, 36, 49, 64]Code language: Python (python)
Expected Output:
Result is {(6, 36), (8, 64), (4, 16), (5, 25), (3, 9), (7, 49), (2, 4)}
Show Hint
Use the zip() function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it.
Show Solution
Exercise 6: Set Intersection and Removal
Write a code to find the intersection (common) of two sets and remove those elements from the first set.
See: Python Set
Given:
first_set = {23, 42, 65, 57, 78, 83, 29}
second_set = {57, 83, 29, 67, 73, 43, 48}Code language: Python (python)
Expected Output:
Intersection is {57, 83, 29}
First Set after removing common element {65, 42, 78, 23}
Show Hint
- Use the
intersection()andremove()method of a set
Show Solution
- Get the common items using the
first_set.intersection(second_set) - Next, iterate common items using a for loop
- In each iteration, use the
remove()method of on first set and pass the current item to it.
Exercise 7: Subset or Superset of another set
Write a code to checks if one set is a subset or superset of another set. If found, delete all elements from that set.
Given:
first_set = {27, 43, 34}
second_set = {34, 93, 22, 27, 43, 53, 48}Code language: Python (python)
Expected Output:
First set is subset of second set - True
Second set is subset of First set - False
First set is Super set of second set - False
Second set is Super set of First set - True
First Set set()
Second Set {67, 73, 43, 48, 83, 57, 29}
Show Hint
Use the below methods of a set class
issubset()issuperset()clear()
Show Solution
Exercise 8: Filter List Against Dictionary Values
Write a program to iterate a given list and check if a given element exists as a key’s value in a dictionary. If not, delete it from the list
Given:
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}Code language: Python (python)
Expected Outcome:
After removing unwanted elements from list [47, 69, 76, 97]
Show Solution
Exercise 9: Extract Unique Dictionary Values to List
Write a code to get all values from the dictionary and add them to a list but don’t add duplicates
Given:
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}Code language: Python (python)
Expected Outcome:
[47, 52, 44, 53, 54]
Show Solution
Exercise 10: remove duplicates from a list
Write a code to remove duplicates from a list and create a tuple and find the minimum and maximum number
Given:
sample_list = [87, 45, 41, 65, 94, 41, 99, 94]Code language: Python (python)
Expected Outcome:
unique items [87, 45, 41, 65, 99] tuple (87, 45, 41, 65, 99) min: 41 max: 99
Show Solution
sample_list = [87, 52, 44, 53, 54, 87, 52, 53]
print("Original list", sample_list)
sample_list = list(set(sample_list))
print("unique list", sample_list)
t = tuple(sample_list)
print("tuple ", t)
print("Minimum number is: ", min(t))
print("Maximum number is: ", max(t))Code language: Python (python)
Great site!
Perhaps there’s a mistake in Ex 2:
list1 = [54, 44, 27, 79, 91, 41]
should be:
sample_list = [34, 54, 67, 89, 11, 43, 94]
Q3: My answer to solve this question is
lst = [11, 45, 8, 23, 14, 12, 78, 45, 89]
start = 0
end = len(lst)
for i in range(start,end,3):
print(list(reversed(lst[i:i+3])))
Hi, there is an error in Exercise 2:
Given list is [54, 44, 27, 79, 91, 41], but in answer is [34, 54, 67, 89, 11, 43, 94].
Change it for the future.
The website is really good to start!
Q8. Alternative answer:
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {‘Jhon’:47, ‘Emma’:69, ‘Kelly’:76, ‘Jason’:97}
b = []
for key,value in sample_dict.items():
if value in roll_number:
b.append(value)
print(“after removing unwanted elements from list:”, b)
Q8. Alternative answer:
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {‘Jhon’:47, ‘Emma’:69, ‘Kelly’:76, ‘Jason’:97}
b = []
for key,value in sample_dict.items():
if value in roll_number:
b.append(value)
print(“after removing unwanted elements from list:”, b)
Q4. Short answer:
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
dict_list = {}
for i in sample_list:
dict_list[i] = sample_list.count(i)
print(dict_list)
Exercise 10:
Expected outcome is incorrect.
sample_list = [87, 45, 41, 65, 94, 41, 99, 94]
unique items [87, 45, 41, 65, 99]
41 should not be in the unique items list
EXERCISE : 4
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
data = dict()
for i in range(len(sample_list)):
data.update({sample_list[i]:sample_list.count(sample_list[i])})
print(“Printing count of each item : “,data)
Just wanted to say that this is a great list of quizzes for beginners to learn and brush up on Python skills.
Big thanks and keep up the good work.
exercise:10
sample_list = [87, 45, 41, 65, 94, 41, 99, 94]l=list()
for i in sample_list:
if i not in l:
l.append(i)
print("unique items",l)
tup=tuple(l)
print("tuple" ,tup)
print("min: ",min(l),"\nmax: ",max(l))
Exercise 8:
some change to the existing code.I Hope it’s helpful to you..
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
lst=list()
for item in roll_number:
if item in sample_dict.values():
lst.append(item)
print("After removing unwanted elements from list",lst)
Exercise 3:
I Hope this answer is helpful..
#given
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]#solution
c1=sample_list[0:3]print("chunk 1",c1)
#reverse c1
c1.reverse()
print("After reversing it",c1 )
c2=sample_list[3:6]
print("chunk 2",c2)
#reverse c2
c2.reverse()
print("After reversing it ",c2)
c3=sample_list[6:]
print("chunk 3",c3)
#reverse c3
c3.reverse()
print("After reversing it",c3)
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]
l = len(sample_list) // 3
for i in range(0, 3):
chunk = sample_list[i*l:(i+1)*l]
print(f”Chunk {i+1} {chunk}”)
print(f”After reversing it {chunk[::-1]}”)
In Exercise 2 is bug, there are two different lists presented in input and output.
My solution for Exercise 9 (one-liner):
print(list(set(speed.values())))Yup. similar idea:
my_list = list(dict.fromkeys(speed.values()))
For Exercise 8
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
result =[]
for i in roll_number:
if i == i in sample_dict.values():
result.append(i)
print(result)
Question 9 :
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}lst = [set(speed.values())]
print(lst)
Question 10 :
sample_list = [87, 45, 41, 65, 94, 41, 99, 94]
tup = (set(sample_list))
print(max(tup))
print(min(tup))
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}my_set = set(speed.values())
print(list(my_set))
Does this work for exercise 9?
yes it does
For exercise 8
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
result = list()
for i in roll_number:
if i in sample_dict.values():
result.append(i)
else:
result
print(result)
In Exercise 10, the output ought to be:
sample_tuple = (87, 45, 65, 99), because number 41 is duplicated in the original list.for exercise 9
exercise 9
Excellent idea!
Cane same one explain to me exercise N4
Hello
I will propose to you 3 other solutions for #4. Maybe they will help you understand the author’s solution
Hi, Azia this is Naresh I checked your program you don take
Xwhich is not defined in the program that’s why the program throws the error.line count_dict[item] = sample_list.count(x) "remove the x insert the itemthanks
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]count_dict = {}
# print(type(dict))
for item in sample_list:
if item in count_dict.keys():
pass
else:
count_dict[item] = sample_list.count(x)
print('Printing count of each item ', count_dict)
exercise 4
the solution above is for exercise 3 sorry.My alternative for exercise 4 would be the following
Hi there! I am a newbie in Python, so I thought I would share my method of solving Question 7 as my way is a little different from what you guys did. However, the answer is still the same.
exercise 1
Exercise 9:
Exercise 7:
To Exercise 2:
Hi Vishal, thanks for this awesome tutorial. It helped me a lot.
I found a mistake in question Nr. 2
The expected output according to the question should be:
yes, you are right bro.. 🙂
Q1 –
new_list = l1[1:len(l1):2] + l2[0:len(l2):2]Ex- 1
For exercise 6
# We can use set methods “intersection()” and “difference()”
Exercise 5 solution:
Question 8
Question 1
Q4
Exercise 1:
#3
Here’s my solution for #1.
Can you check the Example 2 Question and Answer
Hello
I do not understand
What I did was:
and I got it wrong. What is :: used for?
[x::y]means a slice of thelistOnewhere the
xis the index to start from andyis the step sizeSo, for example;
listOne[0:3]##By the way you can write this aslistOne[::3]I will start from index 0, which is ‘3’
Then I will use the 3rd index from the starting index; which is index 3 = ’12’
So, my result will be;
you have to check indexes that they are odd or even, instead you are checking for elements odd or even
can i get solution for this???
You are required to design the data structure to display the individual player stats for cricket players. A player may have represented more than one team and may have played in more than one format such as Test, ODI and T20.
Problem Statement
Create a list of different data fields and use appropriate Python data types to represent each of them.
Hi,
Exercise 10
I thought that you want to remove all element what was duplicated, but 41 is in unique item
Exercise 10
An alternative way to solve question # 8. I do not know why, but it works! PS: Thank you very much for this website, it’s helping me tremendously!!! =)
Q9:
Q3:
Q3
Can anyone tell me what’s wrong in this code?
it prints after removing unwanted elements from list
[47, 69, 76, 95, 97]Why is 95 still in the list
A solution to question 9
#Given a dictionary get all values from the dictionary and add it in a list but don’t add duplicates
yupp comprehensive lists great
Q.4:
Exercise Question 4
Q5:
You can do this by using set comprehension with zip() function:
my solution for Q4
Hi Vishal,
Thanks for making pynative.com. its really helpful. Given exercise are grt to make some basic concepts.
only request i have is please add some more questions in exercise.
Hey Shivam, Yes I will add more such examples for practice
solution to Q3:
perfect and simple solution. Well done
#Given a list slice it into a 3 equal chunks and reverse each list
Try this for any list length
#Given a list slice it into a 3 equal chunks and reverse each list
Q4
A simple approach for Q.4
Please tell if you like:-))
Hope you liked it:-))
count_dic =dict()
for i in sample_list:
count_dic[i] = sample_list.count(i)
print(count_dic)
thanks a lot for writing this article. its very helpful for me the God give you a long live
question 3
Q9
speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54} set1=set() for values in speed.values(): set1.add(values) print(list(set1))Hi Vishal
What am I doing wrong here? The for loop is ignoring 95 from the list and I can’t find out why
rollNumber = [47, 64, 69, 37, 76, 83, 95, 97] sampleDict ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97} for i in rollNumber: if i not in sampleDict.values(): rollNumber.remove(i) print(f'after removing unwanted elements from list {rollNumber}')I have the same issue when doing it the way you do it Vishal.
But when using the exact code in she given solution it works.
#My code on Q4
OPTION1 list1=[11, 45, 8, 23, 14, 12, 78, 45, 89] limit=int(len(list1)/3) chunk1=[] for i in range(limit): chunk1.append(list1.pop(0)) print(f'Chunk 1 {chunk1}') chunk1.reverse() print(f'After reversing it {chunk1}') chunk2=[] for i in range(limit): chunk2.append(list1.pop(0)) print(f'Chunk 2 {chunk2}') chunk2.reverse() print(f'After reversing it {chunk2}') chunk3=[] for i in range(limit): chunk3.append(list1.pop(0)) print(f'Chunk 3 {chunk3}') chunk3.reverse() print(f'After reversing it {chunk3}') #OPTION2 (Using Function) def chunkandreverse(list1,limit): counter=0 while list1: counter+=1 chunk=[] for i in range(limit): chunk.append(list1.pop(0)) print(f'Chunk {counter} {chunk}') chunk.reverse() print(f'After reversing it {chunk}') chunkandreverse(list1,limit) list1=[11, 45, 8, 23, 14, 12, 78, 45, 89] limit=int(len(list1)/3) chunkandreverse(list1,limit)Apologies for copying twice. I missed the tags as suggested for posting code.
The code I have posted is for Q3
”’
Fixed some defects. Please ignore previous or may be you can compare and see what was fixed. The previous was failing if we added more elements in list. The non function one was simply ignoring elements which were not exact set of 3. Try several possible inputs as below
list1=[11, 45, 8, 23, 14, 12, 78, 45, 89]
list1=[11, 45, 8, 23, 14, 12, 78, 45, 89, 90]
list1=[11, 45, 8, 23, 14, 12, 78, 45, 89, 90, 54]
list1=[11, 45, 8, 23, 14, 12, 78, 45, 89, 90, 54, 12]
”’
#OPTION1 Without Function list1=[11, 45, 8, 23, 14, 12, 78, 45,89,44,33,11,90] limit=int(len(list1)/3) chunk1=[] for i in range(limit): chunk1.append(list1.pop(0)) print(f'Chunk 1 {chunk1}') chunk1.reverse() print(f'After reversing it {chunk1}') chunk2=[] for i in range(limit): chunk2.append(list1.pop(0)) print(f'Chunk 2 {chunk2}') chunk2.reverse() print(f'After reversing it {chunk2}') chunk3=[] for i in range(limit): chunk3.append(list1.pop(0)) if list1: chunk3.extend(list1) print(f'Chunk 3 {chunk3}') chunk3.reverse() print(f'After reversing it {chunk3}') #OPTION2 (Using Function) def chunkandreverse(chunks,list1,limit,counter): counter+=1 chunk=[] for i in range(limit): chunk.append(list1.pop(0)) if chunks == 1: chunk.extend(list1) print(f'Chunk {counter} {chunk}') chunk.reverse() print(f'After reversing it {chunk}') chunks-=1 if chunks > 0: chunkandreverse(chunks,list1,limit,counter) list1=[11, 45, 8, 23, 14, 12, 78, 45,89,44,33,11,90] counter=0 chunks=3 limit=int(len(list1)/chunks) chunkandreverse(chunks,list1,limit,0)solution for Q6:
set1 = {65, 42, 78, 83, 23, 57, 29} set2 = {67, 73, 43, 48, 83, 57, 29} set1.difference_update(set1 & set2) print(set1)I can’t see any reason for if else condition you used in solution 3 !
could you explain please?
Q3:
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89] chunk = len(sample_list)//3 for i in range(0, len(sample_list), chunk): ls = sample_list[i:i+chunk] if i == 0: print("Chunk 1 ", ls) print("After reversing it ", ls[::-1]) elif i == 3: print("Chunk 2", ls) print("After reversing it ", ls[::-1]) else: print("Chunk 3", ls) print("After reversing it ", ls[::-1])Question 3:
Q6:
happy to share this,,42 yrs old beginner ,,love python
sa={65, 42, 78, 83, 23, 57, 29} ba={67, 73, 43, 48, 83, 57, 29} inter_set={x for x in sa for y in ba if x==y} sa_1=[x for x in sa if x not in inter_set] print("First set after removing elemnt",set(sa_1)) print(inter_set)sampleList = [87, 45, 41, 65, 94, 41, 99, 94] my_tuple = () for i in sampleList: if i not in my_tuple: my_tuple += (i,) print(my_tuple) print("The Max Value is" , max(my_tuple)) print("The Minimum Value is ",min(my_tuple))Q10
the expected outcome is wrong and leads to wrong code to solve it compared to the solution.
Given your solution the output should be:
Original list [87, 45, 41, 65, 94, 41, 99, 94]
unique list [65, 99, 41, 45, 87, 94]
tuple (65, 99, 41, 45, 87, 94)
Minimum number is: 41
Maximum number is: 99
94 should be included, as set doesn’t remove both instances of duplicate numbers.
Q9 as variant
speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54} print(list(set(speed.values())))Q6
firstSet = {23, 42, 65, 57, 78, 83, 29} secondSet = {57, 83, 29, 67, 73, 43, 48} print(firstSet - secondSet)Can you really tell from where have you learned python, Your solutions are literally amazing
Q4
s_List = [11, 45, 8, 11, 23, 45, 23, 45, 89] print({i: s_List.count(i) for i in s_List})Q3
sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89] c_size = len(sampleList) // 3 print("", sampleList[c_size - 1::-1], "\n",sampleList[(c_size * 2) - 1:c_size - 1:-1], "\n",sampleList[:(c_size * 2) - 1:-1])Q2
u really did it with a smart way . Thanks for sharing ur way . can u tell me where did u practiced python?
please solve this problem
Scenario
You are required to design the data structure to display the individual player stats for cricket players. A player may have represented more than one team and may have played in more than one format such as Test, ODI and T20.
Problem Statement
Create a list of different data fields and use appropriate Python data types to represent each of them
Q9 – My one-line solution:
Q7 – Slight typo in the Expected Outcome which shows “firstSet = {}” (curly braces), which I must admit is what I was anticipating.
Having read about sets but not having worked with them, I was puzzled as to why my solution was showing “firstSet = set()” (set prefix and round brackets) instead. It was only when I checked against your solution that I discovered we had done essentially the same and obtained the same result! Please amend the expected outcome line to show the correct result and possibly spare others the several minutes of head-scratching I experienced.
I now realise that set() is how you would declare an empty set rather than as {} to differentiate it from an empty dictionary, hence that result. So at least the head-scratching resulted in a little more learning.
Q6 – Or slightly more succinctly in one line:
setA = setA.difference(setA.intersection(setB))
Q4. Purely a matter of personal taste, but I prefer the dict’s setdefault method to testing whether the dict currently contains the term. my solution is therefore:
hopkins = ["Not", "I'll", "not", "carrion", "comfort", "Despair", "not", "feast", "on", "thee"] dic = {} for w in hopkins: dic.setdefault(w.lower(), 0) dic[w.lower()] += 1 print(dic){'not': 3, "i'll": 1, 'carrion': 1, 'comfort': 1, 'despair': 1, 'feast': 1, 'on': 1, 'thee': 1}(And I hope these ‘pre’ tags do what I expect !?!)
Q3 My slightly different approach which pads the original list with None values if necessary to make it exactly divisible into equal thirds:
def thirds_reversed(lst): rem = len(lst)%3 if rem > 0: for i in range(3 - rem): lst.append(None) slice = int(len(lst)/3) thirds = [] for i in range(3): third = lst[i*slice:(i+1)*slice] third.reverse() thirds.append(third) return(thirds) print(thirds_reversed([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))[[4, 3, 2, 1], [8, 7, 6, 5], [None, 11, 10, 9]]
For Q3, If this helps someone –
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89] chunk = len(sample_list)//3 for i in range(0, len(sample_list), chunk): ls = sample_list[i:i+chunk] print(ls[::-1])Output –
Q2 Minor error in the wording. You ask to remove the ‘element at index 4’ – given the example and the solution, this should either read ‘the fourth item in the list’ or ‘the element at index 3’. With the current wording, you should be throwing around 91, not 79.
By the way, a belated thank you for your work on this site. It is providing very useful memory jogging and consolidation for what I have learned to date. I look forward to the numpy and subsequent exercises, which will be mostly breaking new ground for me.