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 include 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: Given two lists create a third list by picking an odd-index element from the first list and even index elements from the second.
Given:
listOne = [3, 6, 9, 12, 15, 18, 21]
listTwo = [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 Solution
listOne = [3, 6, 9, 12, 15, 18, 21]
listTwo = [4, 8, 12, 16, 20, 24, 28]
listThree = list()
oddElements = listOne[1::2]
print("Element at odd-index positions from list one")
print(oddElements)
EvenElement = listTwo[0::2]
print("Element at even-index positions from list two")
print(EvenElement)
print("Printing Final third list")
listThree.extend(oddElements)
listThree.extend(EvenElement)
print(listThree)
Exercise 2: Given a list, remove the element 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:
Original list [34, 54, 67, 89, 11, 43, 94] 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 Solution
sampleList = [34, 54, 67, 89, 11, 43, 94]
print("Original list ", sampleList)
element = sampleList.pop(4)
print("List After removing element at index 4 ", sampleList)
sampleList.insert(2, element)
print("List after Adding element at index 2 ", sampleList)
sampleList.append(element)
print("List after Adding element at last ", sampleList)
Exercise 3: Given a list slice it into 3 equal chunks and reverse each chunk
Given:
sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
Expected Outcome:
Original list [11, 45, 8, 23, 14, 12, 78, 45, 89] 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 Solution
sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
print("Original list ", sampleList)
length = len(sampleList)
chunkSize = int(length/3)
start = 0
end = chunkSize
for i in range(1, 4, 1):
indexes = slice(start, end, 1)
listChunk = sampleList[indexes]
print("Chunk ", i , listChunk)
print("After reversing it ", list(reversed(listChunk)))
start = end
if(i != 2):
end +=chunkSize
else:
end += length - chunkSize
Exercise 4: Iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element
Expected Output:
Original list [11, 45, 8, 11, 23, 45, 23, 45, 89] Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
Show Solution
sampleList = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sampleList)
countDict = dict()
for item in sampleList:
if(item in countDict):
countDict[item] += 1
else:
countDict[item] = 1
print("Printing count of each item ",countDict)
Exercise 5: Given a two list of equal size create a Python set such that it shows the element from both lists in the pair
Expected Output:
First List [2, 3, 4, 5, 6, 7, 8] Second List [4, 9, 16, 25, 36, 49, 64] Result is {(6, 36), (8, 64), (4, 16), (5, 25), (3, 9), (7, 49), (2, 4)}
Show Solution
firstList = [2, 3, 4, 5, 6, 7, 8]
print("First List ", firstList)
secondList = [4, 9, 16, 25, 36, 49, 64]
print("Second List ", secondList)
result = zip(firstList, secondList)
resultSet = set(result)
print(resultSet)
Exercise 6: Given the following two sets find the intersection and remove those elements from the first set
Expected Output:
First Set {65, 42, 78, 83, 23, 57, 29} Second Set {67, 73, 43, 48, 83, 57, 29} Intersection is {57, 83, 29} First Set after removing common element {65, 42, 78, 23}
Show Solution
firstSet = {23, 42, 65, 57, 78, 83, 29}
secondSet = {57, 83, 29, 67, 73, 43, 48}
print("First Set ", firstSet)
print("Second Set ", secondSet)
intersection = firstSet.intersection(secondSet)
print("Intersection is ", intersection)
for item in intersection:
firstSet.remove(item)
print("First Set after removing common element ", firstSet)
Exercise 7: Given two sets, Checks if One Set is a subset or superset of another Set. if the subset is found delete all elements from that set
Given:
firstSet = {27, 43, 34}
secondSet = {34, 93, 22, 27, 43, 53, 48}
Expected Output:
First Set {57, 83, 29} Second Set {67, 73, 43, 48, 83, 57, 29} 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 Solution
firstSet = {57, 83, 29}
secondSet = {57, 83, 29, 67, 73, 43, 48}
print("First Set ", firstSet)
print("Second Set ", secondSet)
print("First set is subset of second set -", firstSet.issubset(secondSet))
print("Second set is subset of First set - ", secondSet.issubset(firstSet))
print("First set is Super set of second set - ", firstSet.issuperset(secondSet))
print("Second set is Super set of First set - ", secondSet.issuperset(firstSet))
if(firstSet.issubset(secondSet)):
firstSet.clear()
if(secondSet.issubset(firstSet)):
secondSet.clear()
print("First Set ", firstSet)
print("Second Set ", secondSet)
Exercise 8: Iterate a given list and Check if a given element already exists in a dictionary as a key’s value if not delete it from the list
Given:
rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
Expected Outcome:
After removing unwanted elements from list [47, 69, 76, 97]
Show Solution
rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
print("List -", rollNumber)
print("Dictionary - ", sampleDict)
rollNumber[:] = [item for item in rollNumber if item in sampleDict.values()]
print("after removing unwanted elemnts from list ", rollNumber)
Exercise 9: Given a dictionary 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())
speedList = list()
for item in speed.values():
if item not in speedList:
speedList.append(item)
print("unique list", speedList)
Exercise 10: Remove duplicate from a list and create a tuple and find the minimum and maximum number
Given:
sampleList = [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
sampleList = [87, 52, 44, 53, 54, 87, 52, 53]
print("Original list", sampleList)
sampleList = list(set(sampleList))
print("unique list", sampleList)
tuple = tuple(sampleList)
print("tuple ", tuple)
print("Minimum number is: ", min(tuple))
print("Maximum number is: ", max(tuple))
Hi,
Exercise 10
I thought that you want to remove all element what was duplicated, but 41 is in unique item
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:-))
thanks a lot for writing this article. its very helpful for me the God give you a long live
question 3
Q9
Hi Vishal
What am I doing wrong here? The for loop is ignoring 95 from the list and I can’t find out why
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
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]
”’
solution for Q6:
I can’t see any reason for if else condition you used in solution 3 !
could you explain please?
Q3:
Question 3:
Q6:
happy to share this,,42 yrs old beginner ,,love python
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
Q6
Can you really tell from where have you learned python, Your solutions are literally amazing
Q4
Q3
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:
(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:
[[4, 3, 2, 1], [8, 7, 6, 5], [None, 11, 10, 9]]
For Q3, If this helps someone –
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.