This data structure exercise is for beginners to understand and practice basic data structure in Python. Practice Python List, Set, Dictionary, and Tuple questions.
The data structure is widely used to hold any data. To perform any programming tasks in Python, good knowledge of data structure is a must.
Solve this exercise to have a good understanding of basic data structure in Python
This Exercise includes the followings
- The exercise contains 10 questions and solution provided for each question
- Questions cover list manipulation, dictionary, set, and tuple methods.
Use Online Code Editor to solve exercise questions.
Exercise 1: Create a list by picking an odd-index items from the first list and even index items 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]
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
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
res = list()
odd_elements = list1[1::2]
print("Element at odd-index positions from list one")
print(odd_elements)
even_elements = list2[0::2]
print("Element at even-index positions from list two")
print(even_elements)
print("Printing Final third list")
res.extend(odd_elements)
res.extend(even_elements)
print(res)
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]
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.
sample_list = [34, 54, 67, 89, 11, 43, 94]
print("Original list ", sample_list)
element = sample_list.pop(4)
print("List After removing element at index 4 ", sample_list)
sample_list.insert(2, element)
print("List after Adding element at index 2 ", sample_list)
sample_list.append(element)
print("List after Adding element at last ", sample_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]
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,
start
andend
value will change
sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]
print("Original list ", sample_list)
length = len(sample_list)
chunk_size = int(length / 3)
start = 0
end = chunk_size
# run loop 3 times
for i in range(3):
# get indexes
indexes = slice(start, end)
# get chunk
list_chunk = sample_list[indexes]
print("Chunk ", i, list_chunk)
# reverse chunk
print("After reversing it ", list(reversed(list_chunk)))
start = end
end += chunk_size
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]
Expected Output:
Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
Show Solution
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)
count_dict = dict()
for item in sample_list:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)
Exercise 5: 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]
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
first_list = [2, 3, 4, 5, 6, 7, 8]
print("First List ", first_list)
second_list = [4, 9, 16, 25, 36, 49, 64]
print("Second List ", second_list)
result = zip(first_list, second_list)
result_set = set(result)
print(result_set)
Exercise 6: 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}
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.
first_set = {23, 42, 65, 57, 78, 83, 29}
second_set = {57, 83, 29, 67, 73, 43, 48}
print("First Set ", first_set)
print("Second Set ", second_set)
intersection = first_set.intersection(second_set)
print("Intersection is ", intersection)
for item in intersection:
first_set.remove(item)
print("First Set after removing common element ", first_set)
Exercise 7: 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}
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
first_set = {57, 83, 29}
second_set = {57, 83, 29, 67, 73, 43, 48}
print("First Set ", first_set)
print("Second Set ", second_set)
print("First set is subset of second set -", first_set.issubset(second_set))
print("Second set is subset of First set - ", second_set.issubset(first_set))
print("First set is Super set of second set - ", first_set.issuperset(second_set))
print("Second set is Super set of First set - ", second_set.issuperset(first_set))
if first_set.issubset(second_set):
first_set.clear()
if second_set.issubset(first_set):
second_set.clear()
print("First Set ", first_set)
print("Second Set ", second_set)
Exercise 8: 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}
Expected Outcome:
After removing unwanted elements from list [47, 69, 76, 97]
Show Solution
roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {'Jhon': 47, 'Emma': 69, 'Kelly': 76, 'Jason': 97}
print("List:", roll_number)
print("Dictionary:", sample_dict)
# create new list
roll_number[:] = [item for item in roll_number if item in sample_dict.values()]
print("after removing unwanted elements from list:", roll_number)
Exercise 9: 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}
Expected Outcome:
[47, 52, 44, 53, 54]
Show Solution
speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53,
'july': 54, 'Aug': 44, 'Sept': 54}
print("Dictionary's values - ", speed.values())
speed_list = list()
# iterate dict values
for val in speed.values():
# check if value not present in a list
if val not in speed_list:
speed_list.append(val)
print("unique list", speed_list)
Exercise 10: 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]
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))
akri_ma says
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!
fateme says
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)
fateme says
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)
fateme says
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)
Nvm says
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
Muhammad Usman says
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)
Anon says
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.
Mahesh Reddy says
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))
Mahesh Reddy says
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)
Mahesh Reddy says
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)
Adrian says
In Exercise 2 is bug, there are two different lists presented in input and output.
Miri says
My solution for Exercise 9 (one-liner):
print(list(set(speed.values())))
Peri says
Yup. similar idea:
my_list = list(dict.fromkeys(speed.values()))
Shubham Navghare says
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)
Vishal Soni says
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))
Anton D says
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?
Monishree RmeshBabu says
yes it does
Khan says
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)
arek says
In Exercise 10, the output ought to be:
sample_tuple = (87, 45, 65, 99)
, because number 41 is duplicated in the original list.luke says
swat says
swat says
for exercise 9
pavan says
exercise 9
hiom says
Cane same one explain to me exercise N4
Azia says
Hello
I will propose to you 3 other solutions for #4. Maybe they will help you understand the author’s solution
naresh irigineni says
Hi, Azia this is Naresh I checked your program you don take
X
which 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 item
thanks
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)
Swats says
Alvin says
exercise 4
Alvin says
the solution above is for exercise 3 sorry.My alternative for exercise 4 would be the following
Kai says
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.
sonali says
exercise 1
Rishikesh Shah says
Exercise 9:
Rishikesh Shah says
Exercise 7:
Rishikesh Shah says
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:
harshul Patel says
yes, you are right bro.. 🙂
Aditya Patel says
Q1 –
new_list = l1[1:len(l1):2] + l2[0:len(l2):2]
Rishikesh Shah says
Ex- 1
zxenon_ says
For exercise 6
# We can use set methods “intersection()” and “difference()”
RT says
Exercise 5 solution:
suman says
Maria says
Danilo says
Question 8
Danilo says
Question 1
sama71 says
Q4
mar says
Shiv says
Mazhar says
Exercise 1:
Mark Kustelski says
#3
Andy Lee Parker says
Here’s my solution for #1.
Narender says
Can you check the Example 2 Question and Answer
Hobby Programer says
Hello
I do not understand
What I did was:
and I got it wrong. What is :: used for?
frk_th says
[x::y]
means a slice of thelistOne
where the
x
is the index to start from andy
is 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;
Raju says
Chandini Maheshwari says
VIKRAM says
you have to check indexes that they are odd or even, instead you are checking for elements odd or even
happy says
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.
Pawel says
Hi,
Exercise 10
I thought that you want to remove all element what was duplicated, but 41 is in unique item
Narmin says
Narmin says
Exercise 10
Marco says
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!!! =)
Sat says
Q9:
Sat says
Q3:
someboi says
Q3
Naruto Uzumaki says
Suman kumar Shrestha says
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
haddad says
Danilo says
Rajkumar says
A solution to question 9
Raghu says
#Given a dictionary get all values from the dictionary and add it in a list but don’t add duplicates
nikhil says
yupp comprehensive lists great
CaraDoCoidgo says
Q.4:
DMS KARUNARATNE says
Exercise Question 4
Galbatrollix says
Q5:
You can do this by using set comprehension with zip() function:
sheena says
my solution for Q4
Shivam says
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.
Vishal says
Hey Shivam, Yes I will add more such examples for practice
Dalvir says
solution to Q3:
Charan says
perfect and simple solution. Well done
Raghu Varier says
#Given a list slice it into a 3 equal chunks and reverse each list
Try this for any list length
Raghu says
#Given a list slice it into a 3 equal chunks and reverse each list
Saurabh says
Q4
A simple approach for Q.4
Please tell if you like:-))
Hope you liked it:-))
maya says
count_dic =dict()
for i in sample_list:
count_dic[i] = sample_list.count(i)
print(count_dic)
bostan Khan says
thanks a lot for writing this article. its very helpful for me the God give you a long live
Narendra says
question 3
Olli says
Ramneek Singh says
Q9
Ramneek Singh says
Hi Vishal
What am I doing wrong here? The for loop is ignoring 95 from the list and I can’t find out why
Pieter says
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.
Ramneek Singh says
#My code on Q4
Ramneek Singh says
Apologies for copying twice. I missed the tags as suggested for posting code.
The code I have posted is for Q3
Ramneek Singh says
”’
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]
”’
Nupur says
solution for Q6:
ershad says
I can’t see any reason for if else condition you used in solution 3 !
could you explain please?
Nikhil K says
Q3:
Ali says
Question 3:
Maria says
Lakhtibi Mourad says
Q6:
happy to share this,,42 yrs old beginner ,,love python
Collins Oyugi says
Giorgos says
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.
Vitaliy says
Q9 as variant
Vitaliy says
Q6
Saurabh says
Can you really tell from where have you learned python, Your solutions are literally amazing
Vitaliy says
Q4
Vitaliy says
Q3
Vitaliy says
Q2
amine says
u really did it with a smart way . Thanks for sharing ur way . can u tell me where did u practiced python?
Rohan says
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
zubair khalid says
Bill Hardwick says
Q9 – My one-line solution:
Bill Hardwick says
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.
Bill Hardwick says
Q6 – Or slightly more succinctly in one line:
setA = setA.difference(setA.intersection(setB))
Bill Hardwick says
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:
(And I hope these ‘pre’ tags do what I expect !?!)
Bill Hardwick says
Q3 My slightly different approach which pads the original list with None values if necessary to make it exactly divisible into equal thirds:
[[4, 3, 2, 1], [8, 7, 6, 5], [None, 11, 10, 9]]
Varun says
For Q3, If this helps someone –
Output –
Bill Hardwick says
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.