27th Nov 2023 12 minutes read 12 Beginner-Level Python List Exercises with Solutions Luke Hande python python programming Need to improve your Python programming skills? In this article, we give you 12 Python list exercises so you can master working with this common data structure. A data structure is a way of organizing and storing data. Python has several built-in data structures, including lists, arrays, tuples, and dictionaries. They all have different properties, making them useful in different situations. See our article Array vs. List in Python - What’s the Difference? for some specific details. Lists are particularly useful since they’re very flexible. Therefore, becoming proficient in working with lists in Python is an important step towards becoming a good programmer. In this article, we’ll teach you how Python lists work. We’ll go over 12 exercises designed to teach you different aspects of storing and manipulating data in lists. And don’t worry; detailed solutions are provided. We’ll start with beginner-friendly basics and work our way up to more advanced concepts. Some of these exercises are taken directly from two of our courses, Python Basics Part 2 and Python Data Structures in Practice. These courses include 74 and 118 exercises, respectively. Other exercises in this article are inspired by the content available in the courses. They should give you a feel for the type and quality of the learning material available on LearnPython.com. Before We Get Started... To make sure we’re all on the same page before we start solving the exercises, let’s cover the basics of Python lists. An empty list can be created with square brackets ([]) or with Python’s built-in list() function. We’ll use the first method to create an empty list called data: >>> data = [] We can organize and store data in a list. Let’s create the list again, but this time with some integers separated by a comma: >>> data = [1, 1, 2, 3, 5, 8, 13] A list can store many different data types. Let’s define a list with four strings: >>> colors = ['red', 'blue', 'green', 'yellow'] When a list is created, each element is assigned a unique integer index. The first element has the index 0, the second has the index 1, and so on. Python lists have many methods associated with them, some of which we’ll be using in these exercises. For some background reading, check out An Overview of Python List Methods. That’s about all you need to know at this point. Let’s get started with some exercises. Exercise 1: Accessing List Elements... or Not Here are a series of mini-exercises to get you warmed up. Using the colors list defined above, print the: First element. Second element. Last element. Second-to-last element. Second and third elements. Element at index 4. Solution print(colors[0]) 'red' print(colors[1]) 'blue' print(colors[-1]) 'yellow' print(colors[-2]) 'green' print(colors[1:3]) ['blue', 'green'] print(colors[4]) IndexError: list index out of range This exercise is very fundamental to understanding how lists work. The key to solving this problem is to remember that indexing in Python starts from zero. That is, the first element has the index 0, the second has the index 1, and so on. Also, the last element has the index -1, the second to last has the index -2, and so on. Finally, trying to access an element using an index which isn’t present gives an IndexError. You’ll have to become friends with this error, because you’ll meet it all the time in your programming career. For more details on this exercise, check out the article How to Fix the “List index out of range” Error in Python. In this exercise, we use the print() function to display the results. Since you’ll be using this built-in function often, check out Printing a List in Python – 10 Tips and Tricks for more details about how to use this function. Exercise 2: Assigning New Values to List Elements Below is a list with seven integer values representing the daily water level (in cm) in an imaginary lake. However, there is a mistake in the data. The third day’s water level should be 693. Correct the mistake and print the changed list. water_level = [730, 709, 682, 712, 733, 751, 740] Solution water_level[2] = 693 print(water_level) [730, 709, 693, 712, 733, 751, 740] This exercise builds off the previous one. You need to access the third element, which has the index 2, and simply reassign the value to 693. Then you print the modified list to see if the change was done correctly. Exercise 3: Adding New Elements to the List Add the data for the eighth day to the list from above. The water level was 772 cm on that day. Print the list contents afterwards. Solution water_level.append(772) print(water_level) [730, 709, 693, 712, 733, 751, 740, 772] The list.append() method is one of the most important list methods. It’s used to add a new element to the end of the list. After doing so, the length of the list will increase by one. Exercise 4: Adding Multiple New Elements to the List Still using the same list, add three consecutive days using a single instruction. The water levels on the 9th through 11th days were 772 cm, 770 cm, and 745 cm. Add these values and then print the whole list. Solution new_data = [772, 770, 745] water_level = water_level + new_data print(water_level) [730, 709, 693, 712, 733, 751, 740, 772, 772, 770, 745] We first have to define a new list, which we call new_data. This new list contains the three consecutive values we want to add to the water_level list. Then we use the addition operator (+) to concatenate the two lists. Using the assignment operator (=), we assign the results back to the water_level list for the changes to be permanent. Finally, we print the modified list to check the results. Exercise 5: Deleting a Value from the List There are two ways to delete data from a list: by using the index or by using the value. Start with the original water_level list we defined in the second exercise and delete the first element using its index. Then define the list again and delete the first element using its value. Solution water_level = [730, 709, 682, 712, 733, 751, 740] del water_level[0] print(water_level) [709, 682, 712, 733, 751, 740] water_level = [730, 709, 682, 712, 733, 751, 740] water_level.remove(730) print(water_level) [709, 682, 712, 733, 751, 740] Start by defining the list. To delete the first element using its index, use the del operator. Note: Make sure you define the correct element to delete. If you just execute del water_level, you’ll delete the whole list. For the second method, start again by defining the list. To delete the first element based on its value, use the list.remove() method. It takes one argument: the value to delete. If the value occurs multiple times in the list, only the first one will be deleted. Exercise 6: Conditional Statements You are given a list of 12 values in a variable named tourist_arrivals. The values represent the number of tourists (in millions) that visited France in each month of 2016. Write a program that will ask the user for a number and will check if there is any month with a value that exactly matches the input number. If there is such a month, print: ‘Value found’. Otherwise, print ‘Value not found’. tourist_arrivals = [7.8, 9.0, 10.4, 10.9, 14.7, 15.6, 22.7, 22.3, 14.8, 11.4, 8.6, 9.1] Solution number = float(input('Enter monthly arrivals: ')) if number in tourist_arrivals: print('Value found') else: print('Value not found') We start with our list, which contains floats. Using the input() built-in function, we can accept user input from the keyboard and assign the input to the variable number. Then, using an if-else statement, we test if number is in our list. If so, we print ‘Value found’; if not, we print ‘Value not found’. Exercise 7: Iterating Over List Elements by Value Below is a list containing Martha’s monthly spending. Her monthly spending falls into three categories: Low: Less than0 Medium: Between 2000.0 and 3000.0 High: Greater than0 Analyze monthly_spending, create low, medium and high variables, and print the following sentence: ‘Martha’s spending was low for {x} months, medium for {y} months and high for {z} months.’ monthly_spending = [2689.56, 2770.38, 2394.04, 2099.91, 3182.20, 3267.12, 1746.83, 2545.72, 3328.20, 3147.30, 2462.61, 3890.45, 3000.00, 2000.00] Solution low=0 medium=0 high=0 for spending in monthly_spending: if spending < 2000: low += 1 elif 2000 <= spending <= 3000: medium += 1 else: high += 1 print('Martha\'s spending was low for', low,'months, medium for', medium,'months and high for', high,'months.') We start by creating three new variables: low, medium, and high, all initialized to zero to store the number of months with spending in the respective categories. Then we loop through the values of the list and use an if-elif-else block to check which category that amount falls into. We use the += operator to increase the counters by one, and in the final line we print the results. Exercise 8: Iterating Over List Elements by Index Martha is interested in knowing her average expenses for each half of the year. Compute her average expenses for the first half of the year (January to June) and for the second half of the year (July to December). Display the information as follows: Average expense Jan-June: {1st half-year average} Average expense July-Dec: {2nd half-year average} Solution monthly_spending = [2689.56, 2770.38, 2394.04, 2099.91, 3182.20, 3267.12, 1746.83, 2545.72, 3328.20, 3147.30, 2462.61, 3890.45] sum_expenses = [0, 0] for index in range(len(monthly_spending)): if index < 6: sum_expenses[0] += monthly_spending[index] else: sum_expenses[1] += monthly_spending[index] print('Average expense Jan-June: {}'.format(sum_expenses[0] / 6)) print('Average expense July-Dec: {}'.format(sum_expenses[1] / 6)) We start with our monthly_spending list. To store the results, we create a list with two elements, both zero. Then we loop through the indexes of the list. The index tells us the month (0 = January, 1 = February, …, 6 = July, … 11 = December). We test if the expense is from earlier than July by testing if the index is less than 6. If so, we use the index to access the value from the monthly_spending list and add the expense to the first element of our sum_expenses list. If not, we add the expense to the second element of our sum_expenses list. In the Python Data Structures in Practice course, we show you a more concise way to solve the same problem that takes advantage of the enumerate() built-in function. Exercise 9: Creating New Lists Based on Existing Ones Martha’s expenses are currently expressed in USD. Create a new list named monthly_spending_eur that contains the same expenditures converted into euros. Use the exchange rate of 1 USD = 0.88 EUR. Round the EUR value to two decimal places using round(value, 2). Then, print monthly_spending_eur list. Solution monthly_spending = [2689.56, 2770.38, 2394.04, 2099.91, 3182.20, 3267.12, 1746.83, 2545.72, 3328.20, 3147.30, 2462.61, 3890.45] monthly_spending_eur = [] for spending in monthly_spending: monthly_spending_eur.append(round(spending * 0.88, 2)) print(monthly_spending_eur) The key to solving this exercise is to initialize an empty list outside the loop. This list will store our expenses in euros. Then we loop through the expenses and append the converted amounts to the new list with the list.append() method. Finally, we print the new list. Exercise 10: Comparing Two Lists of Different Sizes In 2017, Martha had two credit cards: one that she used during the whole year, and another that she only used for the first six months. Below you have the monthly spending values from both cards. Your task is to create a new list containing total monthly spending for the entirety of 2017. Round the sums to integers and print the list. spending_card1 = [3231.22, 3039.49, 2813.55, 2271.80, 1922.53, 2335.07] spending_card2 = [3883.04, 3073.93, 3727.18, 2340.49, 1651.91, 1585.41, 2025.84, 3367.66, 2442.75, 2395.70, 3328.55, 3453.42] Solution total_spending = [] if len(spending_card1) > len(spending_card2): longer_len = len(spending_card1) else: longer_len = len(spending_card2) for i in range(longer_len): monthly_total = 0 if i < len(spending_card1): monthly_total += spending_card1[i] if i < len(spending_card2): monthly_total += spending_card2[i] total_spending.append(round(monthly_total)) print(total_spending) We first need to figure out how long the longest list is. This is what the first if-else statement does. Using the built-in function len(), the length is saved as the variable longer_len. We then loop through all integers from 0 to longer_len-1 using the built-in range() function. These integers represent the index of our lists. At the top of the loop, we define another variable monthly_total, which is zero. We have another if statement to check if our integer is less than the length of the respective lists. If so, we add the amount from either or both the spending_card1 or spending_card2 lists to the monthly_total variable. This variable then gets appended to our total_spending list. Working with more than one list at a time is common. Our article How to Loop Over Multiple Lists in Python contains more examples that show you how to handle multiple Python lists. Exercise 11: Working with Lists Inside Functions Write a function named get_long_words(input_list, min_len). The function accepts a list of strings and returns a new list containing only words at least as long as the minimum length provided as the second argument (min_len). Use the list below to test your function: sample_words = ['bird', 'carpet', 'bicycle', 'orange', 'floccinaucinihilipilification'] Solution def get_long_words(input_list, min_len): list_to_return = [] for i in input_list[:]: if len(i) >= min_len: list_to_return.append(i) return list_to_return Exercise 12: Modifying Lists in a Function Create a function called get_absolute_values() that takes a list and modifies it so that all numbers are given as absolute values (i.e., get rid of the minus sign for negative numbers). Do not return anything. Test the function using the following list: absolutes = [13, -15, 42, -165, 32, -678, 1, 41] Solution def get_absolute_values(input_list): for i in range(0, len(input_list)): if input_list[i] < 0: input_list[i] = -input_list[i] Here we loop through the input list using the index of the elements. Using the index, we test if the element is less than zero. If so, we change the sign of the element in the original list. Test the function by running: >>> get_absolute_values(absolutes) Since the function doesn’t return anything, you’ll need to call the absolutes list again to check how it has been modified. In the course, we also showed you how to do the same by not modifying the original list. It’s important to understand the differences between these two cases. Do You Need More Python List Exercises? The course material presented here exposes you to many programming concepts and the exercises are structured to build on top of each other. In this way, you progressively develop new skills. The material in the Python Basics Part 2 and Python Data Structures in Practice courses also shows you how not to solve problems and why certain approaches don’t work. For example, if you want to delete several elements from your list in a loop, you can’t just use the list.remove() method. In the courses, we explain why and show you the correct way. The courses also cover many more aspects of working with Python lists than we can show in this article, such as sorting lists. For an overview of this topic, read the articles How to Sort a List of Tuples in Python and How to Sort a List Alphabetically in Python. Happy learning, and we’ll see you in the next article. Tags: python python programming