Python Practice for Beginners: 15 Hands-On Problems

There’s no denying that solving Python exercises is one of the best ways to practice and improve your Python skills. Hands-on engagement with the language is essential for effective learning. This is exactly what this article will help you with: we've curated a diverse set of Python practice exercises tailored specifically for beginners seeking to test their programming skills.

These Python practice exercises cover a spectrum of fundamental concepts, all of which are covered in our Python Data Structures in Practice and Built-in Algorithms in Python courses. Together, both courses add up to 39 hours of content. They contain over 180 exercises for you to hone your Python skills. In fact, the exercises in this article were taken directly from these courses!

In these Python practice exercises, we will use a variety of data structures, including lists, dictionaries, and sets. We’ll also practice basic programming features like functions, loops, and conditionals. Every exercise is followed by a solution and explanation. The proposed solution is not necessarily the only possible answer, so try to find your own alternative solutions. Let’s get right into it!

Python Practice Problem 1: Average Expenses for Each Semester

John has a list of his monthly expenses from last year:

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]

He wants to know his average expenses for each semester. Using a for loop, calculate John’s average expenses for the first semester (January to June) and the second semester (July to December).

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] first_semester_total = 0 second_semester_total = 0 for index, expense in enumerate(monthly_spending): if index < 6: first_semester_total += expense else: second_semester_total += expense first_semester_avg = first_semester_total / 6 second_semester_avg = second_semester_total / 6 print("Average expenses for the first semester:", first_semester_avg) print("Average expenses for the second semester:", second_semester_avg)

Explanation

We initialize two variables, first_semester_total and second_semester_total , to store the total expenses for each semester. Then, we iterate through the monthly_spending list using enumerate() , which provides both the index and the corresponding value in each iteration. If you have never heard of enumerate() before – or if you are unsure about how for loops in Python work – take a look at our article How to Write a for Loop in Python.

Within the loop, we check if the index is less than 6 (January to June); if so, we add the expense to first_semester_total . If the index is greater than 6, we add the expense to second_semester_total .

After iterating through all the months, we calculate the average expenses for each semester by dividing the total expenses by 6 (the number of months in each semester). Finally, we print out the average expenses for each semester.

Python Practice Problem 2: Who Spent More?

John has a friend, Sam, who also kept a list of his expenses from last year:

john_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] sam_monthly_spending = [1969.62, 3939.37, 2241.59, 3968.27, 3068.80, 1755.02, 3885.66, 2491.67, 3828.49, 3171.32, 2771.32, 3380.37]

They want to find out how many months John spent more money than Sam. Use a for loop to compare their expenses for each month. Keep track of the number of months where John spent more money.

Solution

john_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] sam_monthly_spending = [1969.62, 3939.37, 2241.59, 3968.27, 3068.80, 1755.02, 3885.66, 2491.67, 3828.49, 3171.32, 2771.32, 3380.37] months_john_spent_more = 0 for i in range(len(john_monthly_spending)): if john_monthly_spending[i] > sam_monthly_spending[i]: months_john_spent_more += 1 print("Number of months John spent more money than Sam:", months_john_spent_more)

Explanation

We initialize the variable months_john_spent_more with the value zero. Then we use a for loop with range(len()) to iterate over the indices of the john_monthly_spending list.

Within the loop, we compare John's expenses with Sam's expenses for the corresponding month using the index i . If John's expenses are greater than Sam's for a particular month, we increment the months_john_spent_more variable. Finally, we print out the total number of months where John spent more money than Sam.

Python Practice Problem 3: All of Our Friends

Paul and Tina each have a list of their respective friends:

paul_friends = ["Mary", "Tim", "Mike", "Henry"] tina_friends = ["Tim", "Susan", "Mary", "Josh"]

Combine both lists into a single list that contains all of their friends. Don’t include duplicate entries in the resulting list.

Solution

paul_friends = ["Mary", "Tim", "Mike", "Henry"] tina_friends = ["Tim", "Susan", "Mary", "Josh"] combined_friends = list(set(paul_friends + tina_friends)) print("Combined list of friends:", combined_friends)

Explanation

There are a few different ways to solve this problem. One option is to use the + operator to concatenate Paul and Tina's friend lists ( paul_friends and tina_friends ). Afterwards, we convert the combined list to a set using set() , and then convert it back to a list using list() . Since sets cannot have duplicate entries, this process guarantees that the resulting list does not hold any duplicates. Finally, we print the resulting combined list of friends.

Python Practice Problem 4: Find the Common Friends

Now, let’s try a different operation. We will start from the same lists of Paul’s and Tina’s friends:

paul_friends = ["Mary", "Tim", "Mike", "Henry"] tina_friends = ["Tim", "Susan", "Mary", "Josh"]

In this exercise, we’ll use a for loop to get a list of their common friends.

Solution

paul_friends = ["Mary", "Tim", "Mike", "Henry"] tina_friends = ["Tim", "Susan", "Mary", "Josh"] common_friends = [] for friend in paul_friends: if friend in tina_friends: common_friends.append(friend) print("Common friends:", common_friends)

Explanation

For this problem, we use a for loop to iterate through each friend in Paul's list ( paul_friends ). Inside the loop, we check if the current friend is also present in Tina's list ( tina_friends ). If it is, it is added to the common_friends list. This approach guarantees that we test each one of Paul’s friends against each one of Tina’s friends. Finally, we print the resulting list of friends that are common to both Paul and Tina.

Python Practice Problem 5: Find the Basketball Players

You work at a sports club. The following sets contain the names of players registered to play different sports:

football_players = volleyball_players = basketball_players =

How can you obtain a set that includes the players that are only registered to play basketball (i.e. not registered for football or volleyball)?

Solution

football_players = volleyball_players = basketball_players = basketball_only_players = basketball_players - (football_players | volleyball_players) print("Basketball-only players:", basketball_only_players)

Explanation

This type of scenario is exactly where set operations shine. Don’t worry if you never heard about them: we have an article on Python set operations with examples to help get you up to speed.

First, we use the | (union) operator to combine the sets of football and volleyball players into a single set. In the same line, we use the - (difference) operator to subtract this combined set from the set of basketball players. The result is a set containing only the players registered for basketball and not for football or volleyball.

If you prefer, you can also reach the same answer using set methods instead of the operators:

basketball_only_players = basketball_players.difference(football_players.union(volleyball_players))

It’s essentially the same operation, so use whichever you think is more readable.

Python Practice Problem 6: Count the Votes

Let’s try counting the number of occurrences in a list. The list below represent the results of a poll where students were asked for their favorite programming language:

poll_results = ["Python", "Java", "Javascript", "Python", "Javascript", "Python", "C", "Python", "Python", "C", "Javascript"]

Use a dictionary to tally up the votes in the poll.

Solution

poll_results = ["Python", "Java", "Javascript", "Python", "Javascript", "Python", "C", "Python", "Python", "C", "Javascript"] vote_tally = <> for language in poll_results: if language in vote_tally: vote_tally[language] += 1 else: vote_tally[language] = 1 print("Vote Tally:", vote_tally)

Explanation

In this exercise, we utilize a dictionary ( vote_tally ) to count the occurrences of each programming language in the poll results. We iterate through the poll_results list using a for loop; for each language, we check if it already is in the dictionary. If it is, we increment the count; otherwise, we add the language to the dictionary with a starting count of 1. This approach effectively tallies up the votes for each programming language.

If you want to learn more about other ways to work with dictionaries in Python, check out our article on 13 dictionary examples for beginners.

Python Practice Problem 7: Sum the Scores

Three friends are playing a game, where each player has three rounds to score. At the end, the player whose total score (i.e. the sum of each round) is the highest wins. Consider the scores below (formatted as a list of tuples):

scores = [('Mike', 10), ('Mike', 8), ('Mike', 6), ('John', 7), ('John', 8), ('John', 5), ('John', 8), ('Tom', 8), ('Tom', 9)]

Create a dictionary where each player is represented by the dictionary key and the corresponding total score is the dictionary value.

Solution

scores = [('Mike', 10), ('Mike', 8), ('Mike', 6), ('John', 7), ('John', 8), ('John', 5), ('Tom', 8), ('Tom', 8), ('Tom', 9)] total_scores = <> for player, score in scores: if player in total_scores: total_scores[player] += score else: total_scores[player] = score print("Total Scores:", total_scores)

Explanation

This solution is similar to the previous one. We use a dictionary ( total_scores ) to store the total scores for each player in the game. We iterate through the list of scores using a for loop, extracting the player's name and score from each tuple. For each player, we check if they already exist as a key in the dictionary. If they do, we add the current score to the existing total; otherwise, we create a new key in the dictionary with the initial score. At the end of the for loop, the total score of each player will be stored in the total_scores dictionary, which we at last print.

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

numbers = [10, 3, 5, 9, 18, 3, 0, 7]

… write a function that returns a tuple containing the list’s maximum value, sum of values, and mean value.

Solution

numbers = [10, 3, 5, 9, 18, 3, 0, 7] def calculate_statistics(input_list): max_value = max(input_list) sum_values = sum(input_list) mean_value = sum_values / len(input_list) return max_value, sum_values, mean_value result = calculate_statistics(numbers) print("Maximum value:", result[0]) print("Sum of values:", result[1]) print("Mean value:", result[2])

Explanation

We create a function called calculate_statistics to calculate the required statistics from a list of numbers. This function utilizes a combination of max() , sum() , and len() to obtain these statistics. The results are then returned as a tuple containing the maximum value, the sum of values, and the mean value.

The function is called with the provided list and the results are printed individually.

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

word_list = ["apple", "airplane", "carrot", "elephant", "guitar", "moonlight"]

… find the longest and the shortest word in the list.

Solution

word_list = ["apple", "airplane", "carrot", "elephant", "guitar", "moon"] longest_word = word_list[0] shortest_word = word_list[0] for word in word_list: if len(word) > len(longest_word): longest_word = word elif len(word) < len(shortest_word): shortest_word = word print("Longest word:", longest_word) print("Shortest word:", shortest_word)

Explanation

To find the longest and shortest word in the list, we initialize the variables longest_word and shortest_word as the first word in the list. Then we use a for loop to iterate through the word list. Within the loop, we compare the length of each word with the length of the current longest and shortest words. If a word is longer than the current longest word, it becomes the new longest word; on the other hand, if it's shorter than the current shortest word, it becomes the new shortest word. After iterating through the entire list, the variables longest_word and shortest_word will hold the corresponding words.

There’s a catch, though: what happens if two or more words are the shortest? In that case, since the logic used is to overwrite the shortest_word only if the current word is shorter – but not of equal length – then shortest_word is set to whichever shortest word appears first. The same logic applies to longest_word , too. If you want to set these variables to the shortest/longest word that appears last in the list, you only need to change the comparisons to = (greater or equal than), respectively.

If you want to learn more about Python strings and what you can do with them, be sure to check out this overview on Python string methods.

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

number_list = [5, 8, 2, 7, 3, 5, 6, 9, 2, 4, 8, 7, 1, 5, 3]

… create a new list containing only the numbers that occur at least three times in the list.

Solution

number_list = [5, 2, 2, 7, 3, 5, 6, 9, 2, 2, 8, 7, 1, 5, 3] filtered_list = [] for num in number_list: if number_list.count(num) >= 3: filtered_list.append(num) print("Numbers occurring at least three times:", filtered_list)

Explanation

Here, we use a for loop to iterate through the number_list . In the loop, we use the count() method to check if the current number occurs at least three times in the number_list . If the condition is met, the number is appended to the filtered_list .

After the loop, the filtered_list contains only numbers that appear three or more times in the original list.

Python Practice Problem 11: The Second-Best Score

You’re given a list of students’ scores in no particular order:

exam_results = [23, 78, 96, 32, 53, 67, 23, 98, 33, 38, 45, 39, 86, 12, 43, 45]

Find the second-highest score in the list.

Solution

exam_results = [23, 78, 96, 32, 53, 67, 23, 98, 33, 38, 45, 39, 86, 12, 43, 45] exam_results.sort() second_best_score = exam_results[-2] print("Second best score:", second_best_score)

Explanation

This one is a breeze if we know about the sort() method for Python lists – we use it here to sort the list of exam results in ascending order. This way, the highest scores come last. Then we only need to access the second to last element in the list (using the index -2 ) to get the second-highest score.

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

list_one = [1, 2, 3, 2, 1] list_two = [1, 1, 2, 2, 3]

… create a function that returns whether a list is symmetrical. In this case, a symmetrical list is a list that remains the same after it is reversed – i.e. it’s the same backwards and forwards.

Solution

list_one = [1, 2, 3, 2, 1] list_two = [1, 1, 2, 2, 3] def is_symmetrical(input_list): reversed_list = input_list.copy() reversed_list.reverse() return reversed_list == input_list result_one = is_symmetrical(list_one) result_two = is_symmetrical(list_two) print("Is list_one symmetrical?", result_one) print("Is list_two symmetrical?", result_two)

Explanation

Reversing a list can be achieved by using the reverse() method. In this solution, this is done inside the is_symmetrical function.

To avoid modifying the original list, a copy is created using the copy() method before using reverse() . The reversed list is then compared with the original list to determine if it’s symmetrical.

The remaining code is responsible for passing each list to the is_symmetrical function and printing out the result.

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

fruits = ["Apple", "Banana", "Cherry", "Melon", "Strawberry", "Orange"]

… sort the list by the number of vowels in each word. Words with fewer vowels should come first.

Solution

fruits = ["Apple", "Banana", "Cherry", "Melon", "Strawberry", "Orange"] def count_vowels(word): count = 0 for char in word: if char.lower() in "aeiou": count += 1 return count sorted_fruits = sorted(fruits, key=count_vowels) print("Sorted fruits by the number of vowels:", sorted_fruits)

Explanation

Whenever we need to sort values in a custom order, the easiest approach is to create a helper function. In this approach, we pass the helper function to Python’s sorted() function using the key parameter. The sorting logic is defined in the helper function.

In the solution above, the custom function count_vowels uses a for loop to iterate through each character in the word, checking if it is a vowel in a case-insensitive manner. The loop increments the count variable for each vowel found and then returns it. We then simply pass the list of fruits to sorted() , along with the key=count_vowels argument.

Python Practice Problem 14: Sorting a Mixed List

Imagine you have a list with mixed data types: strings, integers, and floats:

mixed_list = ["apple", 5, 3.14, "banana", 7, 2.5, "orange", 10, 1.618, "grape"]

Typically, you wouldn’t be able to sort this list, since Python cannot compare strings to numbers. However, writing a custom sorting function can help you sort this list.

Create a function that sorts the mixed list above using the following logic:

Solution

mixed_list = ["apple", 5, 3.14, "banana", 7, 2.5, "orange", 10, 1.618, "grape"] def custom_sort(element): if isinstance(element, str): return len(element) elif isinstance(element, (int, float)): return element sorted_mixed_list = sorted(mixed_list, key=custom_sort) print("Sorted mixed list:", sorted_mixed_list)

Explanation

As proposed in the exercise, a custom sorting function named custom_sort is defined to handle the sorting logic. The function checks whether each element is a string or a number using the isinstance() function. If the element is a string, it returns the length of the string for sorting; if it's a number (integer or float), it returns the number itself.

The sorted() function is then used to sort the mixed_list using the logic defined in the custom sorting function.

If you’re having a hard time wrapping your head around custom sort functions, check out this article that details how to write a custom sort function in Python.

Python Practice Problem 15: Filter and Reorder

Given another list of strings, such as the one below ..

things = ["Car", "Computer", "Building", "Bed", "Microwave", "TV"]

.. create a function that does two things: filters out any words with three or fewer characters and sorts the resulting list alphabetically.

Solution

things = ["Car", "Computer", "Building", "Bed", "Microwave", "TV"] def filter_and_sort(input_list): filtered_list = [] for word in input_list: if len(word) > 3: filtered_list.append(word) sorted_list = sorted(filtered_list) return sorted_list result = filter_and_sort(things) print("Filtered and sorted list:", result)

Explanation

Here, we define filter_and_sort , a function that does both proposed tasks.

First, it uses a for loop to filter out words with three or fewer characters, creating a filtered_list . Then, it sorts the filtered list alphabetically using the sorted() function, producing the final sorted_list .

The function returns this sorted list, which we print out.

Want Even More Python Practice Problems?

We hope these exercises have given you a bit of a coding workout. If you’re after more Python practice content, head straight for our courses on Python Data Structures in Practice and Built-in Algorithms in Python, where you can work on exciting practice exercises similar to the ones in this article.

Additionally, you can check out our articles on Python loop practice exercises, Python list exercises, and Python dictionary exercises. Much like this article, they are all targeted towards beginners, so you should feel right at home!