w3resource

Python Data Type: List - Exercises, Practice, Solution

Python List [82 exercises with solution]

[An editor is available at the bottom of the page to write and execute the scripts.]

1. Write a Python program to sum all the items in a list. Go to the editor
Click me to see the sample solution

2. Write a Python program to multiplies all the items in a list. Go to the editor
Click me to see the sample solution

3. Write a Python program to get the largest number from a list. Go to the editor
Click me to see the sample solution

4. Write a Python program to get the smallest number from a list. Go to the editor
Click me to see the sample solution

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. Go to the editor
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
Click me to see the sample solution

6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Go to the editor
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Click me to see the sample solution

7. Write a Python program to remove duplicates from a list. Go to the editor
Click me to see the sample solution

8. Write a Python program to check a list is empty or not. Go to the editor
Click me to see the sample solution

9. Write a Python program to clone or copy a list. Go to the editor
Click me to see the sample solution

10. Write a Python program to find the list of words that are longer than n from a given list of words. Go to the editor
Click me to see the sample solution

11. Write a Python function that takes two lists and returns True if they have at least one common member. Go to the editor
Click me to see the sample solution

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements. Go to the editor
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
Click me to see the sample solution

13. Write a Python program to generate a 3*4*6 3D array whose each element is *. Go to the editor
Click me to see the sample solution

14. Write a Python program to print the numbers of a specified list after removing even numbers from it. Go to the editor
Click me to see the sample solution

15. Write a Python program to shuffle and print a specified list. Go to the editor
Click me to see the sample solution

16. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included). Go to the editor
Click me to see the sample solution

17. Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included). Go to the editor
Click me to see the sample solution

18. Write a Python program to generate all permutations of a list in Python. Go to the editor
Click me to see the sample solution

19. Write a Python program to get the difference between the two lists. Go to the editor
Click me to see the sample solution

20. Write a Python program access the index of a list. Go to the editor
Click me to see the sample solution

21. Write a Python program to convert a list of characters into a string. Go to the editor
Click me to see the sample solution

22. Write a Python program to find the index of an item in a specified list. Go to the editor
Click me to see the sample solution

23. Write a Python program to flatten a shallow list. Go to the editor
Click me to see the sample solution

24. Write a Python program to append a list to the second list. Go to the editor
Click me to see the sample solution

25. Write a Python program to select an item randomly from a list. Go to the editor
Click me to see the sample solution

26. Write a python program to check whether two lists are circularly identical. Go to the editor
Click me to see the sample solution

27. Write a Python program to find the second smallest number in a list. Go to the editor
Click me to see the sample solution

28. Write a Python program to find the second largest number in a list. Go to the editor
Click me to see the sample solution

29. Write a Python program to get unique values from a list. Go to the editor
Click me to see the sample solution

30. Write a Python program to get the frequency of the elements in a list. Go to the editor
Click me to see the sample solution

31. Write a Python program to count the number of elements in a list within a specified range. Go to the editor
Click me to see the sample solution

32. Write a Python program to check whether a list contains a sublist. Go to the editor
Click me to see the sample solution

33. Write a Python program to generate all sublists of a list. Go to the editor
Click me to see the sample solution

34. Write a Python program using Sieve of Eratosthenes method for computing primes upto a specified number. Go to the editor
Note: In mathematics, the sieve of Eratosthenes, (Ancient Greek: κόσκινον Ἐρατοσθένους, kóskinon Eratosthénous) one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit.
Click me to see the sample solution

35. Write a Python program to create a list by concatenating a given list which range goes from 1 to n. Go to the editor
Sample list : ['p', 'q']
n =5
Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5']
Click me to see the sample solution

36. Write a Python program to get variable unique identification number or string. Go to the editor
Click me to see the sample solution

37. Write a Python program to find common items from two lists. Go to the editor
Click me to see the sample solution

38. Write a Python program to change the position of every n-th value with the (n+1)th in a list. Go to the editor
Sample list: [0,1,2,3,4,5]
Expected Output: [1, 0, 3, 2, 5, 4]
Click me to see the sample solution

39. Write a Python program to convert a list of multiple integers into a single integer. Go to the editor
Sample list: [11, 33, 50]
Expected Output: 113350
Click me to see the sample solution

40. Write a Python program to split a list based on first character of word. Go to the editor
Click me to see the sample solution

41. Write a Python program to create multiple lists. Go to the editor
Click me to see the sample solution

42. Write a Python program to find missing and additional values in two lists. Go to the editor
Sample data : Missing values in second list: b,a,c
Additional values in second list: g,h
Click me to see the sample solution

43. Write a Python program to split a list into different variables. Go to the editor
Click me to see the sample solution

44. Write a Python program to generate groups of five consecutive numbers in a list. Go to the editor
Click me to see the sample solution

45. Write a Python program to convert a pair of values into a sorted unique array. Go to the editor
Click me to see the sample solution

46. Write a Python program to select the odd items of a list. Go to the editor
Click me to see the sample solution

47. Write a Python program to insert an element before each element of a list. Go to the editor
Click me to see the sample solution

48. Write a Python program to print a nested lists (each list on a new line) using the print() function. Go to the editor
Click me to see the sample solution

49. Write a Python program to convert list to list of dictionaries. Go to the editor
Sample lists: ["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]
Expected Output: [{'color_name': 'Black', 'color_code': '#000000'}, {'color_name': 'Red', 'color_code': '#FF0000'}, {'color_name': 'Maroon', 'color_code': '#800000'}, {'color_name': 'Yellow', 'color_code': '#FFFF00'}]
Click me to see the sample solution

50. Write a Python program to sort a list of nested dictionaries. Go to the editor
Click me to see the sample solution

51. Write a Python program to split a list every Nth element. Go to the editor
Sample list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
Expected Output: [['a', 'd', 'g', 'j', 'm'], ['b', 'e', 'h', 'k', 'n'], ['c', 'f', 'i', 'l']]
Click me to see the sample solution

52. Write a Python program to compute the similarity between two lists. Go to the editor
Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"]
Expected Output:
Color1-Color2: ['white', 'orange', 'red']
Color2-Color1: ['black', 'yellow']
Click me to see the sample solution

53. Write a Python program to create a list with infinite elements. Go to the editor
Click me to see the sample solution

54. Write a Python program to concatenate elements of a list. Go to the editor
Click me to see the sample solution

55. Write a Python program to remove key values pairs from a list of dictionaries. Go to the editor
Click me to see the sample solution

56. Write a Python program to convert a string to a list. Go to the editor
Click me to see the sample solution

57. Write a Python program to check whether all items of a list is equal to a given string. Go to the editor
Click me to see the sample solution

58. Write a Python program to replace the last element in a list with another list. Go to the editor
Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8]
Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8]
Click me to see the sample solution

59. Write a Python program to check whether the n-th element exists in a given list. Go to the editor
Click me to see the sample solution

60. Write a Python program to find a tuple, the smallest second index value from a list of tuples. Go to the editor
Click me to see the sample solution

61. Write a Python program to create a list of empty dictionaries. Go to the editor
Click me to see the sample solution

62. Write a Python program to print a list of space-separated elements. Go to the editor
Click me to see the sample solution

63. Write a Python program to insert a given string at the beginning of all items in a list. Go to the editor
Sample list : [1,2,3,4], string : emp
Expected output : ['emp1', 'emp2', 'emp3', 'emp4']
Click me to see the sample solution

64. Write a Python program to iterate over two lists simultaneously. Go to the editor
Click me to see the sample solution

65. Write a Python program to access dictionary keys element by index. Go to the editor
Click me to see the sample solution

66. Write a Python program to find the list in a list of lists whose sum of elements is the highest. Go to the editor
Sample lists: [1,2,3], [4,5,6], [10,11,12], [7,8,9]
Expected Output: [10, 11, 12]
Click me to see the sample solution

67. Write a Python program to find all the values in a list are greater than a specified number. Go to the editor
Click me to see the sample solution

68. Write a Python program to extend a list without append. Go to the editor
Sample data: [10, 20, 30]
[40, 50, 60]
Expected output : [40, 50, 60, 10, 20, 30]
Click me to see the sample solution

69. Write a Python program to remove duplicates from a list of lists. Go to the editor
Sample list : [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
New List : [[10, 20], [30, 56, 25], [33], [40]]
Click me to see the sample solution

70. Write a Python program to get the depth of a dictionary. Go to the editor
Click me to see the sample solution

71. Write a Python program to check whether all dictionaries in a list are empty or not. Go to the editor
Sample list : [{},{},{}]
Return value : True
Sample list : [{1,2},{},{}]
Return value : False
Click me to see the sample solution

72. Write a Python program to flatten a given nested list structure. Go to the editor
Original list: [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
Flatten list:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
Click me to see the sample solution

73. Write a Python program to remove consecutive duplicates of a given list. Go to the editor
Original list:
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
After removing consecutive duplicates:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4]
Click me to see the sample solution

74. Write a Python program to pack consecutive duplicates of a given list elements into sublists. Go to the editor
Original list:
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
After packing consecutive duplicates of the said list elements into sublists:
[[0, 0], [1], [2], [3], [4, 4], [5], [6, 6, 6], [7], [8], [9], [4, 4]]
Click me to see the sample solution

75. Write a Python program to create a list reflecting the run-length encoding from a given list of integers or a given list of characters. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4.3, 5, 1]
List reflecting the run-length encoding from the said list:
[[2, 1], [1, 2], [1, 3], [1, 4], [1, 4.3], [1, 5], [1, 1]]
Original String:
automatically
List reflecting the run-length encoding from the said string:
[[1, 'a'], [1, 'u'], [1, 't'], [1, 'o'], [1, 'm'], [1, 'a'], [1, 't'], [1, 'i'], [1, 'c'], [1, 'a'], [2, 'l'], [1, 'y']]
Click me to see the sample solution

76. Write a Python program to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
List reflecting the modified run-length encoding from the said list:
[[2, 1], 2, 3, [2, 4], 5, 1]
Original String:
aabcddddadnss
List reflecting the modified run-length encoding from the said string:
[[2, 'a'], 'b', 'c', [4, 'd'], 'a', 'd', 'n', [2, 's']]
Click me to see the sample solution

77. Write a Python program to decode a run-length encoded given list. Go to the editor
Original encoded list:
[[2, 1], 2, 3, [2, 4], 5, 1]
Decode a run-length encoded said list:
[1, 1, 2, 3, 4, 4, 5, 1]
Click me to see the sample solution

78. Write a Python program to split a given list into two parts where the length of the first part of the list is given. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Length of the first part of the list: 3
Splited the said list into two parts:
([1, 1, 2], [3, 4, 4, 5, 1])
Click me to see the sample solution

79. Write a Python program to remove the K'th element from a given list, print the new list. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Length of the first part of the list: 3
Splited the said list into two parts:
([1, 1, 2], [3, 4, 4, 5, 1])
Click me to see the sample solution

80. Write a Python program to insert an element at a specified position into a given list. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
After removing an element at the kth position of the said list:
[1, 1, 3, 4, 4, 5, 1]
Click me to see the sample solution

81. Write a Python program to extract a given number of randomly selected elements from a given list. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Selected 3 random numbers of the above list:
[4, 4, 1]
Click me to see the sample solution

82. Write a Python program to generate the combinations of n distinct objects taken from the elements of a given list. Go to the editor
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9] Combinations of 2 distinct objects: [1, 2] [1, 3] [1, 4] [1, 5] .... [7, 8] [7, 9] [8, 9]
Click me to see the sample solution

List: Cheat Sheet

Making a list:

colors = ['Red', 'Blue', 'Green', 'Black', 'White']

Accessing elements:

# Getting the first element
first_col = colors[0]
# Getting the second element
second_col = colors[1]
# Getting the last element
newest_col = colors[-1]

Modifying individual items:

# Changing an element
colors[0] = 'Yellow'
colors[-2] = 'Red'

Adding elements:

# Adding an element to the end of the list
colors.append('Orange')
# Starting with an empty list
colors = []
colors.append('Red')
colors.append('Blue')
colors.append('Green')
# Inserting elements at a particular position
colors.insert(0, 'Violet')
colors.insert(2, 'Purple')

Removing elements:

# Deleting an element by its position
del colors[-1]
# Removing an item by its value
colors.remove('Green')

Popping elements:

# Pop the last item from a list
most_recent_col = colors.pop()
print(most_recent_col)
# Pop the first item in a list
first_col = colors.pop(0)
print(first_col)

List length:

# Find the length of a list
num_colors = len(colors)
print("We have " + str(num_colors) + " colors.")

Sorting a list:

# Sorting a list permanently
colors.sort()
# Sorting a list permanently in reverse alphabetical order
colors.sort(reverse=True)
# Sorting a list temporarily
print(sorted(colors))
print(sorted(colors, reverse=True))
# Reversing the order of a list
colors.reverse()

Looping through a list:

# Printing all items in a list
for col in colors:
 print(col)
# Printing a message for each item, and a separate message afterwards
for col in colors:
 print("Welcome, " + col + "!")
print("Welcome, we're glad to see you all!")

The range() function:

# Printing the numbers 0 to 2000
for num in range(2001):
 print(num)
# Printing the numbers 1 to 2000
for num in range(1, 2001):
 print(num)
# Making a list of numbers from 1 to a million
nums = list(range(1, 1000001))

Simple statistics:

# Finding the minimum value in a list
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_min = min(nums)
# Finding the maximum value
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_max = max(nums)
# Finding the sum of all numbers
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
total_num = sum(nums)

Slicing a list:

# Getting the first three items
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
first_three = colors [:3]
# Getting the middle three items
middle_three = colors[1:4]
# Getting the last three items
last_three = colors[-3:]

Copying a list:

# Making a copy of a list
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
copy_of_colors = colors[:]

List of Comprehensions:

# Using a loop to generate a list of square numbers
squr = []
for x in range(1, 11):
 sq = x**2
 squr.append(sq)
# Using a comprehension to generate a list of square numbers
squr = [x**2 for x in range(1, 11)]
# Using a loop to convert a list of names to upper case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = []
for cols in colors:
 upper_cols.append(cols.upper())
# Using a comprehension to convert a list of names to upper case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = [cols.upper() for cols in colors]

Python Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: How to install pip on Windows?

Python 2.7.9+ and 3.4+

Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Node.js, Haskell, Perl, Go-almost every other contemporary language with a majority open-source community. Thank you, Python.

If you do find that pip is not available when using Python 3.4+ or Python 2.7.9+, simply execute e.g.:

py -3 -m ensurepip

Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this in the Stack Overflow question Does Python have a package/module management system?.

And, alas for everyone using Python 2.7.8 or earlier (a sizable portion of the community). There's no plan to ship Pip to you. Manual instructions follow.

Python 2 = 2.7.8 and Python 3 = 3.3

Flying in the face of its 'batteries included' motto, Python ships without a package manager. To make matters worse, Pip was-until recently-ironically difficult to install.

Official instructions

Per https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip:

Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt:

python get-pip.py

You possibly need an administrator command prompt to do this. Follow Start a Command Prompt as an Administrator (Microsoft TechNet).

This installs the pip package, which (in Windows) contains ...\Scripts\pip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of 'Alternative Instructions' for adding it to your PATH,

Alternative instructions

The official documentation tells users to install Pip and each of its dependencies from source. That's tedious for the experienced and prohibitively difficult for newbies.

For our sake, Christoph Gohlke prepares Windows installers (.msi) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:

  1. Install setuptools
  2. Install pip

For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (for example, C:\Python27\Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:

pip install httpie

There you go (hopefully)! Solutions for common problems are given below:

Proxy problems

If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables http_proxy and https_proxy. Most Python applications (and other free software) respect these. Example syntax:

http://proxy_url:port
http://username:[email protected]_url:port

If you're really unlucky, your proxy might be a Microsoft NTLM proxy. Free software can't cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. http://cntlm.sourceforge.net/

Unable to find vcvarsall.bat

Python modules can be partly written in C or C++. Pip tries to compile from source. If you don't have a C/C++ compiler installed and configured, you'll see this cryptic error message.

Error: Unable to find vcvarsall.bat

You can fix that by installing a C++ compiler such as MinGW or Visual C++. Microsoft actually ships one specifically for use with Python. Or try Microsoft Visual C++ Compiler for Python 2.7.

Often though it's easier to check Christoph's site for your package.

Ref: https://bit.ly/2B0ch3y