PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python Exercises » Python Data Structure Exercise for Beginners

Python Data Structure Exercise for Beginners

Updated on: March 9, 2021 | Python Tags: Basics Python Python Exercises

TweetF  sharein  shareP  Pin

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

Also Solve:

  • Python List exercise
  • Python Dictionary exercise
  • Python Tuple exercise
  • Python Set exercise

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))

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Basics Python Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

52 Comments

Comments

  1. Pawel says

    March 25, 2021 at 1:38 pm

    Hi,
    Exercise 10

    sampleList = [87, 45, 41, 65, 94, 41, 99, 94]
    unique items [87, 45, 41, 65, 99] missing 94 :)

    I thought that you want to remove all element what was duplicated, but 41 is in unique item

    Reply
  2. Marco says

    March 12, 2021 at 9:31 pm

    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!!! =)

    
    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(rollNumber)
    
    Reply
  3. Sat says

    February 27, 2021 at 7:53 pm

    Q9:

    print(list(set(speed.values())))
    Reply
  4. Sat says

    February 27, 2021 at 4:31 pm

    Q3:

    sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
    chunk  = 3
    for i in range(0, len(sampleList ), chunk):
        print(list1[i:i+chunk][::-1])
    Reply
  5. someboi says

    February 11, 2021 at 11:24 pm

    Q3

    
     def something(list):
        index = int(len(data) / 3)
        i = 0
        while i < index:
            chunk = data[index*i:index*(i+1)]
            chunk = chunk[::-1]
            print(chunk)
            i = i + 1
    
    data = [11, 45, 8, 23, 14, 12, 78, 45, 89]
    something(data)
    Reply
  6. Suman kumar Shrestha says

    February 7, 2021 at 5:04 am

    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

    
    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("after removing unwanted elements from list ", rollNumber)
    Reply
  7. Rajkumar says

    January 12, 2021 at 5:43 pm

    A solution to question 9

    speed ={'jan':47,'feb':52,'march':47,'April':44,'May':52,'June':53, 'july':54, 'Aug':44, 'Sept':54}
    
    new_list = []
    
    for key, val in speed.items():
        if val not in new_list:
            new_list.append(val)
    print(new_list)
    Reply
  8. Raghu says

    November 6, 2020 at 7:20 pm

    #Given a dictionary get all values from the dictionary and add it in a list but don’t add duplicates

    
    speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53, 'july':54, 'Aug':44, 'Sept':54}
    list2[:] = [item for item in speed.values()]
    print(list(set(list2)))
    Reply
    • nikhil says

      December 3, 2020 at 9:37 pm

      yupp comprehensive lists great

      Reply
  9. CaraDoCoidgo says

    September 14, 2020 at 1:57 am

    Q.4:

    lst = [11, 45, 8, 11, 23, 45, 23, 45, 89]
    dc = {}
    for x in lst:
        dc[x] = lst.count(x)
    print(dc)
    Reply
  10. DMS KARUNARATNE says

    September 8, 2020 at 9:46 am

    Exercise Question 4

    from collections import Counter
    orilist=[11, 45, 8, 11, 23, 45, 23, 45, 89]
    z=Counter(orilist)
    print(dict(z))
    Reply
  11. Galbatrollix says

    August 25, 2020 at 1:54 am

    Q5:

    You can do this by using set comprehension with zip() function:

    
    def set_of_pairs(list1,list2):
        return {(x,y) for x,y in zip(list1,list2)}
    Reply
  12. sheena says

    August 18, 2020 at 11:42 am

    my solution for Q4

     Original_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
    dict_new=dict()
    for i in Original_list:
        c=Original_list.count(i)
        dict_new[i]=c
    print(dict_new)
    
    		
    Reply
  13. Shivam says

    August 6, 2020 at 8:07 pm

    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.

    Reply
    • Vishal says

      August 7, 2020 at 11:13 am

      Hey Shivam, Yes I will add more such examples for practice

      Reply
  14. Dalvir says

    July 31, 2020 at 10:54 am

    solution to Q3:

    
    sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
    chunk1 = sampleList[:3]
    print(chunk1[::-1])
    chunk2 = sampleList[3:6]
    print(chunk2[::-1])
    chunk3 = sampleList[6:9]
    print(chunk3[::-1])
    Reply
    • Charan says

      October 18, 2020 at 8:30 pm

      perfect and simple solution. Well done

      Reply
    • Raghu Varier says

      November 6, 2020 at 7:18 pm

      #Given a list slice it into a 3 equal chunks and reverse each list

      list1 = input().split()
      l = len(list1)
      for i in range(0,3):
        sublist = []
        for j in range(i*l//3,(i+1)*l//3):
          sublist.append(list1[j])
        sublist.reverse()
        print(sublist)

      Try this for any list length

      Reply
      • Raghu says

        November 6, 2020 at 7:19 pm

        #Given a list slice it into a 3 equal chunks and reverse each list

        list1 = input().split()
        l = len(list1)
        for i in range(0,3):
          sublist = []
          for j in range(i*l//3,(i+1)*l//3):
            sublist.append(list1[j])
          sublist.reverse()
          print(sublist)
        
        Reply
  15. Saurabh says

    July 13, 2020 at 3:26 am

    Q4
    A simple approach for Q.4
    Please tell if you like:-))

    
    l=[11, 45, 8, 11, 23, 45, 23, 45, 89]
    #creating empty Dictionary
    Count_Dict={}
    for i in l:
        count=0
        for j in l:
            if i==j:
                count+=1
            Count_Dict[i]=count
    print(Count_Dict)

    Hope you liked it:-))

    Reply
  16. bostan Khan says

    June 14, 2020 at 5:22 pm

    thanks a lot for writing this article. its very helpful for me the God give you a long live

    Reply
  17. Narendra says

    June 11, 2020 at 3:16 pm

    question 3

    
    List=[11, 45, 8, 23, 14, 12, 78, 45, 89]
    s = len(List)//2
    chunk1=List[:3]
    chunk2=List[3:s+2]
    chunk3=List[s+2:]
    print('chunck 1',chunk1)
    chunk1.reverse()
    print('After reversed :',chunk1)
    print('chunk 2',chunk2)
    chunk2.reverse()
    print('After reversed :',chunk2)
    print('chunk 3:',chunk3)
    chunk3.reverse()
    print('After reversed :',chunk3)
    
    Reply
    • Olli says

      June 17, 2020 at 3:19 pm

      
      list1 = [11, 45, 8, 23, 14, 12, 78, 45, 89]
      
      chunk_size = int(len(list1)/3)
      
      chunk1 = list1[:chunk_size]
      chunk2 = list1[chunk_size:chunk_size*2]
      chunk3 = list1[chunk_size*2:]
      
      print("Original list", list1)
      print("Chunk 1", chunk1)
      print("After reversing it", chunk1[::-1])
      print("Chunk 2", chunk2)
      print("After reversing it", chunk2[::-1])
      print("Chunk 3", chunk3)
      print("After reversing it", chunk3[::-1])
      
      Reply
  18. Ramneek Singh says

    May 10, 2020 at 4:04 pm

    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))
     
    Reply
  19. Ramneek Singh says

    May 10, 2020 at 1:15 am

    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}')
    
    Reply
    • Pieter says

      August 12, 2020 at 1:01 am

      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.

      Reply
  20. Ramneek Singh says

    May 9, 2020 at 9:21 pm

    #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)
    
    Reply
    • Ramneek Singh says

      May 9, 2020 at 9:25 pm

      Apologies for copying twice. I missed the tags as suggested for posting code.
      The code I have posted is for Q3

      Reply
    • Ramneek Singh says

      May 9, 2020 at 10:39 pm

      ”’
      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)
      
      Reply
  21. Nupur says

    May 9, 2020 at 4:25 am

    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)
    
    Reply
  22. ershad says

    May 5, 2020 at 1:33 am

    I can’t see any reason for if else condition you used in solution 3 !
    could you explain please?

    Reply
  23. Nikhil K says

    May 1, 2020 at 4:03 pm

    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])
    
    Reply
  24. Ali says

    March 23, 2020 at 1:23 pm

    Question 3:

    orgList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
    l1 = orgList[0:3]
    l1.reverse()
    print(l1)
    l2 = orgList[3:6]
    l2.reverse()
    print(l2)
    l3 = orgList[6:9]
    l3.reverse()
    print(l3)
    
    Reply
  25. Lakhtibi Mourad says

    February 14, 2020 at 10:51 am

    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)
    
    Reply
  26. Collins Oyugi says

    December 26, 2019 at 9:10 am

    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))
    
    Reply
  27. Giorgos says

    November 11, 2019 at 3:37 pm

    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.

    Reply
  28. Vitaliy says

    June 21, 2019 at 6:15 pm

    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())))
    
    Reply
  29. Vitaliy says

    June 21, 2019 at 12:35 pm

    Q6

    firstSet = {23, 42, 65, 57, 78, 83, 29}
    secondSet = {57, 83, 29, 67, 73, 43, 48}
    
    print(firstSet - secondSet)
    
    Reply
    • Saurabh says

      July 13, 2020 at 3:32 am

      Can you really tell from where have you learned python, Your solutions are literally amazing

      Reply
  30. Vitaliy says

    June 21, 2019 at 9:57 am

    Q4

    s_List = [11, 45, 8, 11, 23, 45, 23, 45, 89]
    print({i: s_List.count(i) for i in s_List})
    
    Reply
  31. Vitaliy says

    June 20, 2019 at 9:54 pm

    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])
    
    Reply
  32. Vitaliy says

    June 20, 2019 at 9:25 pm

    Q2

    List = [34, 54, 67, 89, 11, 43, 94]
    List[2], List[3], List[4] = List[4], List[2], List[3]
    List.append(List[2])
    print(List)
    
    Reply
    • amine says

      August 30, 2019 at 10:16 pm

      u really did it with a smart way . Thanks for sharing ur way . can u tell me where did u practiced python?

      Reply
  33. Rohan says

    June 15, 2019 at 6:41 pm

    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

    Reply
  34. zubair khalid says

    June 5, 2019 at 6:10 pm

    sampleList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    a = sampleList[:3]
    b = sampleList[3:6]
    c = sampleList[6:9]
    a.reverse()
    b.reverse()
    c.reverse()
    print(a)
    print(b)
    print(c)
    
    Reply
  35. Bill Hardwick says

    May 18, 2019 at 3:14 pm

    Q9 – My one-line solution:

    list_ = list(set(speed.values()))
    Reply
  36. Bill Hardwick says

    May 17, 2019 at 7:33 pm

    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.

    Reply
  37. Bill Hardwick says

    May 17, 2019 at 7:05 pm

    Q6 – Or slightly more succinctly in one line:

    setA = setA.difference(setA.intersection(setB))

    Reply
  38. Bill Hardwick says

    May 17, 2019 at 6:17 pm

    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 !?!)

    Reply
  39. Bill Hardwick says

    May 17, 2019 at 5:56 pm

    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]]

    Reply
    • Varun says

      February 15, 2020 at 9:38 pm

      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 –

      [8, 45, 11]
      [12, 14, 23]
      [89, 45, 78]
      
      Reply
  40. Bill Hardwick says

    May 17, 2019 at 4:22 pm

    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.

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

 Python Exercises

  • Python Exercises Home
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python Regex Python Random Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON
TweetF  sharein  shareP  Pin

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Privacy Policy
  • Cookie Policy
  • Terms Of Use
  • Contact Us
DMCA.com Protection Status

Copyright © 2018-2021 · [pynative.com]