PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python Data Structure Exercise for Beginners

Python Data Structure Exercise for Beginners

Updated on: May 22, 2025 | 119 Comments

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.

Also, Solve:

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

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
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)Code language: Python (python)

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 list
  • append(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)Code language: Python (python)

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 the reversed() function
  • In each iteration, start and end 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_sizeCode language: Python (python)

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
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)Code language: Python (python)

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
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)Code language: Python (python)

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() and remove() 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)Code language: Python (python)

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
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)Code language: Python (python)

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
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)
Code language: Python (python)

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
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)Code language: Python (python)

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)

Filed Under: Python, Python Basics, Python Exercises

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

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics 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

Comments

  1. ImageStef says

    December 26, 2024 at 11:08 pm

    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]

    Reply
  2. Imagevilakshan kaushik says

    May 7, 2024 at 10:45 pm

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

    Reply
  3. Imageakri_ma says

    January 13, 2024 at 8:02 pm

    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!

    Reply
  4. Imagefateme says

    November 15, 2023 at 10:11 am

    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)

    Reply
  5. Imagefateme says

    November 15, 2023 at 10:05 am

    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)

    Reply
  6. Imagefateme says

    November 14, 2023 at 12:35 pm

    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)

    Reply
  7. ImageNvm says

    November 11, 2023 at 7:05 pm

    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

    Reply
  8. ImageMuhammad Usman says

    October 26, 2023 at 10:55 am

    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)

    Reply
  9. ImageAnon says

    April 14, 2023 at 2:45 pm

    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.

    Reply
  10. ImageMahesh Reddy says

    March 7, 2023 at 11:58 am

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

    Reply
  11. ImageMahesh Reddy says

    March 7, 2023 at 1:07 am

    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)

    Reply
  12. ImageMahesh Reddy says

    March 6, 2023 at 10:46 pm

    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)

    Reply
    • ImageJoonatan says

      April 19, 2025 at 6:16 am

      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]}”)

      Reply
  13. ImageAdrian says

    February 3, 2023 at 8:38 pm

    In Exercise 2 is bug, there are two different lists presented in input and output.

    Reply
  14. ImageMiri says

    January 26, 2023 at 1:29 am

    My solution for Exercise 9 (one-liner):

    print(list(set(speed.values())))

    Reply
    • ImagePeri says

      August 24, 2023 at 12:31 pm

      Yup. similar idea:
      my_list = list(dict.fromkeys(speed.values()))

      Reply
  15. ImageShubham Navghare says

    December 21, 2022 at 1:49 am

    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)

    Reply
  16. ImageVishal Soni says

    December 13, 2022 at 12:46 pm

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

    Reply
  17. ImageAnton D says

    December 12, 2022 at 12:20 am

    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?

    Reply
    • ImageMonishree RmeshBabu says

      June 28, 2023 at 1:07 pm

      yes it does

      Reply
  18. ImageKhan says

    November 2, 2022 at 7:07 am

    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)

    Reply
  19. Imagearek says

    October 21, 2022 at 6:43 pm

    In Exercise 10, the output ought to be: sample_tuple = (87, 45, 65, 99), because number 41 is duplicated in the original list.

    Reply
  20. Imageluke says

    August 3, 2022 at 2:39 pm

    exercise1
    l1 = [3, 6, 9, 12, 15, 18, 21]
    l2 = [4, 8, 12, 16, 20, 24, 28]
    l3 = []
    for item in range(1,len(l1)-1+1,2):
        l3.append(l1[item])
    for item2 in range(0,len(l2)-1+1,2):
        l3.append(l2[item2])
    print(l3)
    silution2
    l1 = [3, 6, 9, 12, 15, 18, 21]
    l2 = [4, 8, 12, 16, 20, 24, 28]
    list = [l1[1::2],l2[0::2]]
    
    print(list)
    Reply
  21. Imageswat says

    June 22, 2022 at 1:44 am

    speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53,'july': 54, 'Aug': 44, 'Sept': 54}
    new=set()
    for i in speed.values():
        new.add(i)
    new_1=list(new)
    print(new_1)
    Reply
    • Imageswat says

      June 22, 2022 at 1:45 am

      for exercise 9

      Reply
    • Imagepavan says

      September 23, 2022 at 11:31 am

      exercise 9

      speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}
      list_a=[]
      for i in speed.values():
          if(i not in list_a):
              list_a.append(i)
      print(list_a)
      Reply
    • ImageOkbazghi says

      January 30, 2025 at 12:22 am

      Excellent idea!

      Reply
  22. Imagehiom says

    May 8, 2022 at 4:33 am

    Cane same one explain to me exercise N4

    Reply
    • ImageAzia says

      May 23, 2022 at 9:43 am

      Hello
      I will propose to you 3 other solutions for #4. Maybe they will help you understand the author’s solution

      
      #option 1 - use a set to get distinct elements and then loop on the set
      
      sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
      sample_set = set(sample_list)
      
      dict = {}
      # print(type(dict))
      
      for item in sample_set: 
          dict[item] = sample_list.count(item)
          
      print('Printing count of each item ', dict)
      
      
      -------------------------------------------
      #option 2 - Use a loop
      
      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)
      
      ---------------------------------------
      
      #option 3  - use dictionary comprehension
      
      sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89] 
       
      dict = { k: sample_list.count(k) for k in sample_list}
      print('Printing count of each item ', dict)
      Reply
      • Imagenaresh irigineni says

        October 20, 2022 at 8:57 am

        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)

        Reply
    • ImageSwats says

      June 21, 2022 at 6:03 am

      sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
      my_dic={}
      for i in sample_list:
          count=sample_list.count(i)
          my_dic[i]=count
      print(my_dic)
      Reply
  23. ImageAlvin says

    May 5, 2022 at 6:45 pm

    exercise 4

    s1 = [11, 45, 8, 23, 14, 12, 78, 45, 89]
    lengthChunk=int(len(s1)/3)
    temp=[]
    for x in range(0,9,lengthChunk):
        temp=s1[x:x+lengthChunk]
        temp.reverse()
        print(temp)
    Reply
    • ImageAlvin says

      May 5, 2022 at 6:52 pm

      the solution above is for exercise 3 sorry.My alternative for exercise 4 would be the following

      
      s1 = [11, 45, 8, 11, 23, 45, 23, 45, 89]
      for x in set(s1):
          print(str(x)+":"+str(s1.count(x)))
      Reply
  24. ImageKai says

    April 25, 2022 at 7:23 pm

    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.

    first_set = {27, 43, 34}
    second_set = {34, 93, 22, 27, 43, 53, 48}
    
    a = first_set.issubset(second_set)
    b = second_set.issubset(first_set)
    
    if a == True:
        print("First set is subset of second set - True")
    else:
        print("First set is subset of second set - False")
    if b == True:
        print("Second set is subset of First set - True")
    else:
        print("Second set is subset of First set - False")
    
    c = first_set.issuperset(second_set)
    d = second_set.issuperset(first_set)
    
    if c == True:
        print("First set is Super set of second set - True")
    else:
        print("First set is Super set of second set - False")
        
    if d == True:
        print("Second set is Super set of First set - True")
    else:
        print("Second set is Super set of First set - False")
    
    if a or c == True:
        first_set.clear()
        
    print("First Set", first_set)
    print("Second Set", second_set)
    Reply
  25. Imagesonali says

    April 6, 2022 at 6:09 pm

    exercise 1

    l1=[10,20,30,40,50]
    l2=[10,40,50,60,70,90]
    print(l1[0::2])
    print(l2[1::2])
    Reply
  26. ImageRishikesh Shah says

    April 4, 2022 at 10:11 pm

    Exercise 9:

    import collections
    speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54}
    dict_val = speed.values()
    new_list = [item for item, count in collections.Counter(dict_val).items() if count > 1 or count >= 1]
    print(new_list)
    Reply
  27. ImageRishikesh Shah says

    April 4, 2022 at 8:07 pm

    Exercise 7:

    first_set = {27, 43, 34}
    second_set = {34, 93, 22, 27, 43, 53, 48}
    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 of second set - ", first_set.issuperset(second_set))
    print("Second set is super of First set - ", second_set.issuperset(first_set))
    res_first_set = first_set.difference_update((second_set))
    print("First Set", first_set)
    print("Second Set", second_set)
    Reply
  28. ImageRishikesh Shah says

    March 23, 2022 at 12:39 pm

    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:

    List After removing element at index 4  [54, 44, 27, 79, 41]
    List after Adding element at index 2 [54, 44, 91, 27, 79, 41]
    List after Adding element at last  [54, 44, 91, 27, 79, 41, 91]
    Reply
    • Imageharshul Patel says

      November 3, 2022 at 5:28 pm

      yes, you are right bro.. 🙂

      Reply
  29. ImageAditya Patel says

    March 3, 2022 at 12:45 pm

    Q1 –
    new_list = l1[1:len(l1):2] + l2[0:len(l2):2]

    Reply
    • ImageRishikesh Shah says

      March 23, 2022 at 12:01 pm

      Ex- 1

      l1 = [3, 6, 9, 12, 15, 18, 21]
      l2 = [4, 8, 12, 16, 20, 24, 28]
      odd_list = []
      even_list = []
      new_lst = []
      counter = 0
      for i in range(len(l1)):
          if i % 2 != 0:
              odd_list.append(l1[i])
      print("Element at odd-index position from list one\n", odd_list) 
      for j in range(len(l2)):
          if j % 2 == 0:
              even_list.append(l2[j])
      print("Element at even-index positions from list two\n", even_list)  
      new_lst = [*odd_list, *even_list]  
      print("Printing Final third list\n", new_lst)
      Reply
  30. Imagezxenon_ says

    February 18, 2022 at 2:32 am

    For exercise 6

    # We can use set methods “intersection()” and “difference()”

    first_set = {23, 42, 65, 57, 78, 83, 29}
    second_set = {57, 83, 29, 67, 73, 43, 48}
    
    print(f"Intersection is {first_set.intersection(second_set)}")
    print(f"First set after removing common elements {first_set.difference(first_set.intersection(second_set))}")
    Reply
  31. ImageRT says

    January 18, 2022 at 4:48 pm

    Exercise 5 solution:

    first_list = [2, 3, 4, 5, 6, 7, 8]
    second_list = [4, 9, 16, 25, 36, 49, 64]
    third_list = set()
    
    for i, e in enumerate(first_list):
    	pair = (e, second_list[i])
    	third_list.add(pair)
    print(third_list)
    Reply
    • Imagesuman says

      March 18, 2022 at 11:37 pm

      for i in zip(first_list,second_list):
          print(i)
      Reply
      • ImageMaria says

        April 20, 2022 at 2:40 pm

        
        def list_pairs():
            first_list = [2, 3, 4, 5, 6, 7, 8]
            second_list = [4, 9, 16, 25, 36, 49, 64]
            my_set = [(x, y) for x in first_list for y in second_list if x ** 2 == y]
            print('Result is:', set(my_set))
        
        list_pairs()
        Reply
  32. ImageDanilo says

    December 13, 2021 at 1:21 pm

    Question 8

    
    roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
    sample_dict = {'John':47, 'Emma':69, 'Kelly':76, 'Jason':97}
    
    new_list = []
    for i in roll_number:
        if i in sample_dict.values():
            new_list.append(i)
    
    print("after removing unwanted elements from list:", new_list)
    Reply
  33. ImageDanilo says

    December 10, 2021 at 12:49 pm

    Question 1

    
    l1 = [3, 6, 9, 12, 15, 18, 21]
    l2 = [4, 8, 12, 16, 20, 24, 28]
    
    l1a = [l1[i] for i in range(0, len(l1), 2)] # Odd indexes
    l2a = [l2[j] for j in range(1, len(l2), 2)] # Even indexes
    
    l3 = l1a + l2a # Mix Odd and Even indexes
    
    # Print
    print("Element at odd-index position from list one", "\n", l1a)
    print("Element at even-index position from list two", "\n", l2a)
    print("Printing final third list", "\n", l3)
    Reply
  34. Imagesama71 says

    October 26, 2021 at 1:14 pm

    Q4

    sample = [11, 45, 8, 11, 23, 45, 23, 45, 89]
    dic = {}
    key_list = []
    value_list = []
    for n in sample:
        key_list.append(n)
        c = sample.count(n)
        value_list.append(c)
        
    # first method
        for key in key_list:
            for value in value_list:
                dic[key] = value
    print(dic)             
    
    
    # second method   
    print ({key_list[i] : value_list[i] for i in range(len(key_list))})
             
    
    # third method
    print(dict(zip(key_list, value_list)))
    Reply
    • Imagemar says

      December 21, 2021 at 6:41 pm

      sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
      
      my_dict = {}
      for item in sample_list:
          
          x = sample_list.count(item)
          
          my_dict[item] = x
      
      print('Printing count of each item', my_dict)
      Reply
  35. ImageShiv says

    September 9, 2021 at 1:46 pm

    
    list=[11, 45, 8, 11, 23, 45, 23, 45, 89]
    dict = {}
    for i in range(0,len(list)):
        dict[list[i]] = list.count(list[i])
    print(dict)
    Reply
  36. ImageMazhar says

    September 4, 2021 at 10:32 am

    Exercise 1:

    def check(l1,l2):
        third_list = []
    
        for num in range(1,len(l1),2):
            third_list.append(l1[num])
    
        for num in range(0,len(l2),2):
            third_list.append(l2[num])
    
        print(third_list) 
    
    listOne = [3, 6, 9, 12, 15, 18, 21]
    listTwo = [4, 8, 12, 16, 20, 24, 28]
    check(listOne,listTwo)
    Reply
  37. ImageMark Kustelski says

    August 11, 2021 at 5:01 pm

    #3

    list1 = [11,45,8,23,14,12,78,45,89]
    list2=list1[:3:]
    list3=list1[3:6:]
    list4=list1[6::]
    print(list2[::-1], list3[::-1], list4[::-1])
    Reply
  38. ImageAndy Lee Parker says

    June 28, 2021 at 11:39 pm

    Here’s my solution for #1.

    listOne = [3, 6, 9, 12, 15, 18, 21]
    listTwo = [4, 8, 12, 16, 20, 24, 28]
    listThree = listOne[1::2] + listTwo[0::2]
    print(listThree)
    Reply
  39. ImageNarender says

    May 31, 2021 at 9:39 pm

    Can you check the Example 2 Question and Answer

    Reply
  40. ImageHobby Programer says

    May 25, 2021 at 1:40 am

    Hello
    I do not understand

    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)

    What I did was:

    listOne = [3, 6, 9, 12, 15, 18, 21]
    listTwo = [4, 8, 12, 16, 20, 24, 28]
    odd=[]
    even=[]
    listThree=[]
    for i in listOne:
        if i % 2 == 1:
            odd.append(i)
    for i in listTwo:
        if i % 2 == 0:
            even.append(i)
    for i in odd:
            listThree.append(i)
    for i in even:
            listThree.append(i)
    print("Element at odd-index positions from list one")
    print(odd)
    print("Element at even-index positions from list two")
    print(even)
    print("Printing Final third list")
    print(listThree)

    and I got it wrong. What is :: used for?

    Reply
    • Imagefrk_th says

      May 28, 2021 at 8:53 pm

      listOne = [3, 6, 9, 12, 15, 18, 21]

      [x::y] means a slice of the listOne
      where the x is the index to start from and y is the step size
      So, for example;
      listOne[0:3] ##By the way you can write this as listOne[::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;

      [0, 12, 21]
      
      		
      Reply
    • ImageRaju says

      June 9, 2021 at 2:45 pm

      lst1 = [3, 6, 9, 12, 15, 18, 21]
      lst2= [4, 8, 12, 16, 20, 24, 28]
      odd_index=[]
      even_index=[]
      combo_index=[]
      for i in range (len(lst1)):
          if i%2==1:
              odd_index.append(lst1[i])
              combo_index.append(lst1[i])
      
      print("Elements of odd index list:",odd_index)
      for j in range (len(lst2)):
          if j%2==0:
              even_index.append(lst2[j])
              combo_index.append(lst2[j])
      print("Elements of even index list:",even_index)
      print("Final third list:",combo_index)
      Reply
      • ImageChandini Maheshwari says

        June 14, 2021 at 7:33 pm

        list1=[10,33,77,64,88,63]
        list2=[20,60,77,51,90,11]
        list3=[]
        print("Original List1 is",list1)
        print("Original List2 is",list2)
        print("Odd List is")
        for i in list1:
            if i%2!=0:
                print(i,end=" ")
                list3.append(i)
                print(" ")
        print("Even List is")
        for i in list2:
            if i%2==0:
                print(i,end=" ")
                list3.append(i)
                print(" ")
        print("Merge List1 and List2 is")
        print(list3,end=" ")
        print(" ")
        Reply
    • ImageVIKRAM says

      July 5, 2021 at 9:44 pm

      you have to check indexes that they are odd or even, instead you are checking for elements odd or even

      Reply
  41. Imagehappy says

    May 8, 2021 at 5:42 pm

    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.

    Reply
  42. ImagePawel 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
    • ImageNarmin says

      August 8, 2021 at 12:22 am

      from random import*
      n=int(input("say:"))
      A=[randint(0,100) for i in range(n)]
      print(A)
      B=[]
      for i in range(n):
      	for j in range(n):
      		if A[i]==A[j] and A[i] not in B:
      			B+=[A[i]]
      print(B)
      maxx=A[0]
      minn=A[0]
      for i in range(1,n):
      	if A[i]>maxx:
      			maxx=A[i]
      	if A[i]<minn:
      		minn=A[i]
      print(maxx)
      print(minn)
      Reply
      • ImageNarmin says

        August 8, 2021 at 12:23 am

        Exercise 10

        Reply
  43. ImageMarco 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
  44. ImageSat says

    February 27, 2021 at 7:53 pm

    Q9:

    print(list(set(speed.values())))
    Reply
  45. ImageSat 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
  46. Imagesomeboi 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
    • ImageNaruto Uzumaki says

      September 30, 2021 at 2:33 pm

      sampleList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
      l=len(sampleList)//3
      c=0
      d=[]
      for j in range(1,l+1):
          
          for i in sampleList[c:c+3]:
              
              d.append(i)
              
          print(d[::-1])
          c=c+3
          d=[]
      Reply
  47. ImageSuman 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
    • Imagehaddad says

      August 20, 2021 at 7:20 pm

      rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
      sampleDict ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
      
      for i in rollNumber[::-1]:
          if i not in sampleDict.values():
              rollNumber.remove(i)
      print("after removing unwanted elements from list ", rollNumber)
      
      		
      Reply
    • ImageDanilo says

      December 13, 2021 at 4:43 pm

      
      rollNumber = [47, 64, 69, 37, 76, 83, 95, 97]
      sampleDict ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
      
      for i in rollNumber[0:9]: # or rollNumber[:]  <<<< apparently you need to define the index
          if i not in sampleDict.values():
              rollNumber.remove(i)
      
      print("after removing unwanted elements from list ", rollNumber)
      Reply
  48. ImageRajkumar 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
  49. ImageRaghu 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
    • Imagenikhil says

      December 3, 2020 at 9:37 pm

      yupp comprehensive lists great

      Reply
  50. ImageCaraDoCoidgo 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
  51. ImageDMS 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
  52. ImageGalbatrollix 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
  53. Imagesheena 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
  54. ImageShivam 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
    • ImageVishal says

      August 7, 2020 at 11:13 am

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

      Reply
  55. ImageDalvir 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
    • ImageCharan says

      October 18, 2020 at 8:30 pm

      perfect and simple solution. Well done

      Reply
    • ImageRaghu 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
      • ImageRaghu 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
  56. ImageSaurabh 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
    • Imagemaya says

      November 15, 2023 at 12:27 am

      count_dic =dict()
      for i in sample_list:
      count_dic[i] = sample_list.count(i)

      print(count_dic)

      Reply
  57. Imagebostan 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
  58. ImageNarendra 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
    • ImageOlli 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
  59. ImageRamneek 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
  60. ImageRamneek 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
    • ImagePieter 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
  61. ImageRamneek 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
    • ImageRamneek 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
    • ImageRamneek 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
  62. ImageNupur 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
  63. Imageershad 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
  64. ImageNikhil 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
  65. ImageAli 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
    • ImageMaria says

      April 20, 2022 at 2:12 pm

      def slice_chunks():
          sample_list = [11, 45, 8, 23, 14, 12, 78, 45, 89]
          chunk1 = slice(3)
          chunk2 = slice(3, 6, 1)
          chunk3 = slice(6, 9, 1)
          print('Chunk  1:', sample_list[chunk1])
          reversed1 = list(reversed(sample_list[chunk1]))
          print('After reversing it:', reversed1)
      
          print('Chunk  2:', sample_list[chunk2])
          reversed2 = list(reversed(sample_list[chunk2]))
          print('After reversing it:', reversed2)
      
          print('Chunk  3:', sample_list[chunk3])
          reversed3 = list(reversed(sample_list[chunk3]))
          print('After reversing it:', reversed3)
      
      slice_chunks()
      Reply
  66. ImageLakhtibi 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
  67. ImageCollins 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
  68. ImageGiorgos 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
  69. ImageVitaliy 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
  70. ImageVitaliy 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
    • ImageSaurabh says

      July 13, 2020 at 3:32 am

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

      Reply
  71. ImageVitaliy 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
  72. ImageVitaliy 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
  73. ImageVitaliy 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
    • Imageamine 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
  74. ImageRohan 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
  75. Imagezubair 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
  76. ImageBill Hardwick says

    May 18, 2019 at 3:14 pm

    Q9 – My one-line solution:

    list_ = list(set(speed.values()))
    Reply
  77. ImageBill 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
  78. ImageBill Hardwick says

    May 17, 2019 at 7:05 pm

    Q6 – Or slightly more succinctly in one line:

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

    Reply
  79. ImageBill 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
  80. ImageBill 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
    • ImageVarun 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
  81. ImageBill 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 entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • 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
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

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
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement