30+ List Programs In Python For Practice

List Programs In Python For Practice

In this tutorial, you will get list programs in Python for practice with solutions.

First, we will discuss some general list problems in Python for practice.

Then, you will see some real-life list practice problem.

These real life practice problems will involve real life challenges and their solutions.

So let’s dive in it.

Practice Problem 1: Find the sum of elements in a list

In the first practice problem, you have to find the sum of elements in a list.

First, create a list of integers.

Then, calculate the sum of all the elements.

After that, print the sum on the output screen.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
sum_list = sum(my_list)
print(sum_list)

Output

15

Practice Problem 2: Find the largest number in a list

In the second practice problem, you have to find the largest number in a list.

First, create a list of integers.

Then, find the maximum number in the list using the max() function.

After that, print out the maximum number on the output screen.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [12, 24, 56, 8, 78]
largest_num = max(my_list)
print(largest_num)

Output

78

Practice Problem 3: Find the smallest number in a list

In the third practice problem, you have to find the smallest number in a list.

You can find the smallest number in a list using the min() function.

First, create a list of integers.

Then, find the minimum number of the list using the min() function.

After that, print out the minimum number on the output screen.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [12, 24, 56, 8, 78]
smallest_num = min(my_list)
print(smallest_num)

Output

8

Practice Problem 4: Find the second largest number in a list

In this practice problem, you have to find the second largest number in a list.

You can solve this problem using any method you think possible.

But in this tutorial, we will find the second largest element by first sorting the list using the sort() function.

And then we will find the second largest element using the negative indexing.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [12, 24, 56, 8, 78]
my_list.sort()
second_largest = my_list[-2]
print(second_largest)

Output

56

Practice Problem 5: Remove duplicates from a list

In this practice problem, you have to remove all the duplicate elements from the list.

You can do this by converting you list into a set using the set() function.

A set can only have unique elements.

In this way, all the duplicate will be removed.

After that, you can again convert the set into a list using the list() function.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 2, 4, 5, 1]
unique_list = list(set(my_list))
print(unique_list)

Output

[1, 2, 3, 4, 5]

Practice Problem 6: Check if a list is empty or not

In this practice problem, you have to check if the list is empty or not.

You can check this using the if statement.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = []
if my_list:
    print("List is not empty")
else:
    print("List is empty")

Output

List is empty

Practice Problem 7: Reverse a list

In this practice problem, you have to reverse a list.

First, create a list of integers.

Then, reverse the list using the reverse() method.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

Output

[5, 4, 3, 2, 1]

Practice Problem 8: Count the occurrences of an element in a list

In this practice problem, you have to count the occurrences of an element in a list.

First, create a list in which you want to count the occurrences of an element.

To count the occurrences of an element, you can use built-in count() method.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 2, 4, 5, 2, 1, 2]
count = my_list.count(2)
print(count)

Output

4

Practice Problem 9: Remove all occurrences of an element from a list

In the above problem, you figured out how you can count the number of occurrences of an element.

But how you can remove all the occurrence of an element from a list?

Let’s find out.

You can iterate through the list using a for loop

Then you can use an if statement to check if the current element is not equal to the element that you want to remove.

Give it a try on our free Online Python Compiler before moving to solution.

Here is how it will work:

Solution

my_list = [1, 2, 3, 2, 4, 5, 2, 1, 2]
new_list = []
for x in my_list:
    if x!=2:
        new_list.append(x)
    
print("My List :", my_list)
print("New List : ", new_list)

Output

My List : [1, 2, 3, 2, 4, 5, 2, 1, 2]
New List : [1, 3, 4, 5, 1]

Practice Problem 10: Check if two lists are equal or not

In the practice problem, you have to check if two lists are equal or not.

First, create two lists that you want to compare.

Then compare both list using == operator.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

list1 = [1, 2, 3]
list2 = [1, 2, 3]
if list1 == list2:
    print("Lists are equal")
else:
    print("Lists are not equal")

Output

Lists are equal

Practice Problem 11: Find the average of elements in a list

In this practice problem, you have to find average of all the elements in a list.

To find the average, you have to find sum of all the elements of the list.

And then divide it by the number of elements in the list.

You can use the sum() function to find the sum.

And, the len() function to find the length of the list.

After that, simply divide the sum by the length.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
avg = sum(my_list) / len(my_list)
print(avg)

Output

3.0

Practice Problem 12: Find the common elements between two lists

In the list practice problem, you have to find the common elements between two lists.

To find the common elements, FIrst you have to convert both lists into sets using the set() function.

Then, you can find the common elements using the & operator.

Finally, you have to convert this set into a list using the list() function.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = list(set(list1) & set(list2))
print(common_elements)

Output

[3, 4, 5]

Practice Problem 13: List Programs In Python For Practice

In this practice problem, you have to sort a list in ascending order.

First, create a list of intergers that you want to sort.

Next, sort the list using the sort() method.

And that’s it. You are all done.

You have sorted the list in ascending order.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [5, 1, 3, 2, 4]
my_list.sort()
print(my_list)

Output

[1, 2, 3, 4, 5]

Practice Problem 14: Sort a list in descending order

In this list practice problem, you have to sort a list in descending order.

This practice problem is similar to the above problem except one thing.

You have to pass reverse=True as an argument to the sort() method.

But before moving to the solution, give it a try on our free Online Python Compiler.

Solution

my_list = [5, 1, 3, 2, 4]
my_list.sort(reverse=True)
print(my_list)

Output

[5, 4, 3, 2, 1]

Practice Problem 15: Find the index of an element in a list

In this practice problem, you have to find the index of an element in a list.

Finding the index of an element in a list is really easy in Python.

You can simply use built-in index() method to find the index of an element.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
index = my_list.index(3)
print(index)

Output

2

Practice Problem 16: Insert an element at a specific position in a list

In this practice problem, you have to insert an element to a specific position in a list.

You can use the built-in insert() method to insert an element to a specific position.

You can do this by passing the element and the position as an argument to the insert()

Here is the syntax:

Syntax

insert(position, element)

Give it a try on our free Online Python Compiler before moving to solution.

Here is how you can do it.

Solution

my_list = [1, 2, 3, 5, 6]
my_list.insert(3, 9)
print(my_list)

Output

[1, 2, 3, 9, 5, 6]

Practice Problem 17: Remove an element from a list by its value

In this practice problem, you have to remove an element from a list by its value.

First, create a list of elements.

Then, use the remove() method to remove the element from the list.

Syntax of remove()

remove(element)

Just pass the element as an argument to the remove() method and you are all done.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)

Output

[1, 2, 4, 5]

Practice Problem 18: Remove an element from a list by its index

In this practice problem you have to remove an element from a list by its index.

There are multiple ways to do it.

But in tutorial, we will do it using the del operator.

Here is the basic syntax of how you can use the del operator to remove an element by its index.

Syntax

del list_name[index]

Just create a list of elements.

Then, use the del operator to remove an element by its index.

And that’s it.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list)

Output

[1, 2, 4, 5]

Practice Problem 19: Concatenate two lists

In this practice problem, you have to write the code to concatenate two lists.

Just create two lists that you want to concatenate.

Then concatenate both lists using the + operator.

And that’s it, you are done.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)

Output

[1, 2, 3, 4, 5, 6]

Practice Problem 20: Create a nested list

In this practice problem, you have to create a nested list in Python.

A nested list in Python is a list that contains one or more lists as its elements.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

my_list = [[1, 2], [3, 4], [5, 6]]
print(my_list)

Output

[[1, 2], [3, 4], [5, 6]]

Practice Problem 21: Create a list with a range of values

In this practice problem, you have to create a list with a range of values.

You can use the range() function to do this.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

my_list = list(range(1, 6))
print(my_list)

Output

[1, 2, 3, 4, 5]

Practice Problem 22: Randomly shuffle the elements of a list

In this practice problem, you have to randomly shuffle the elements of a list.

To do this, you can use the shuffle() method of the random module.

First, create a list of integers.

Then, shuffle the list using the shuffle() method.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

Output

[2, 1, 3, 4, 5]

The list will be shuffled every time you run the program.

Practice Problem 23: Flatten a nested list

In this practice problem, you have to flatten a nested list.

First, create a nested list.

Then, iterate through the list using a nested for loop to access each element.

Here’s how it will work.

Solution

my_list = [[1, 2], [3, 4], [5, 6]]
flattened_list = []
for sublist in my_list:
    for element in sublist:
        flattened_list.append(element)
        
print(flattened_list)

Output

[1, 2, 3, 4, 5, 6]

Using this technique, you can flatten any nested list into a normal list.

Real Life Problems

List Programs In Python For Practice (Some Real Life Problems)

Till now, you were practicing basic list problems.

Now, let’s take a look at some real-life problems.

And problems that you can relate with.

Practice Problem 24: Sort a list of dictionaries based on a specific key

In this practice problem, you have to sort a list of dictionaries based on a specific key.

This can be very useful.

Let’s say you have an online store

And you want to sort the product by price.

Or you have a list of employees and you want to sort it by their age.

The possibilities are endless.

You can use it the way you want.

For now, create a dictionary that holds the name and age of a person.

Then sort this dictionary by age.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

my_list = [{'name': 'Alice', 'age': 25},
           {'name': 'Bob', 'age': 20},
           {'name': 'Charlie', 'age': 30}]
sorted_list = sorted(my_list, key=lambda x: x['age']) 
print("Original List :", my_list)
print("Sorted List :", sorted_list)

Output

Original List : [{‘name’: ‘Alice’, ‘age’: 25}, {‘name’: ‘Bob’, ‘age’: 20}, {‘name’: ‘Charlie’, ‘age’: 30}]
Sorted List : [{‘name’: ‘Bob’, ‘age’: 20}, {‘name’: ‘Alice’, ‘age’: 25}, {‘name’: ‘Charlie’, ‘age’: 30}]

Keep in mind, we used lambda function

Because you can’t pass the key as key='age' as the sorted() method accepts only function as a key argument.

Practice Problem 25: Advanced List Programs In Python For Practice

Problem: In a grocery store, there are different types of fruits available with their prices per pound. Write a Python program to take the name of the fruit from the user and the weight in pounds they want to buy. Then, calculate the total cost of the purchase and display it to the user.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Define the prices per pound for each fruit
fruit_prices = {
    "apple": 1.99,
    "banana": 0.99,
    "orange": 2.49,
    "pear": 1.79,
}

# Ask the user for the name of the fruit and the weight in pounds they want to buy
fruit_name = input("Enter the name of the fruit: ")
fruit_weight = float(input("Enter the weight in pounds: "))

# Calculate the total cost of the purchase
if fruit_name in fruit_prices:
    fruit_price = fruit_prices[fruit_name]
    total_cost = fruit_price * fruit_weight
    print(f"Total cost of {fruit_weight:.2f} pounds of {fruit_name} is ${total_cost:.2f}")
else:
    print(f"{fruit_name} is not available in the store")

Output

Enter the name of the fruit: orange
Enter the weight in pounds: 2
Total cost of 2.00 pounds of orange is $4.98

Explanation

We define a dictionary called fruit_prices in this program.

Which contains the cost per pound of each fruit.

Then, we used the input() function to prompt the user for the name of the fruit and the desired purchase weight in pounds.

After that, we check the fruit’s availability using an if statement by seeing if its name appears in the fruit_prices dictionary.

If so, we multiply the price per pound by the weight in pounds to determine the total cost of the purchase.

And then we use the print() function to show the user the total price.

We display an error message if the fruit isn’t available in the store.

Practice Problem 26: Advanced List Programs In Python For Practice

Problem: A teacher wants to calculate the average grade of the students in her class. Write a program to take the number of students and their grades as input and calculate the average. Display the average grade to the user.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Ask the user for the number of students
num_students = int(input("Enter the number of students: "))

# Initialize a variable to store the sum of grades
total_grade = 0

# Ask the user for the grades of each student and add it to the total grade
for i in range(num_students):
    grade = float(input(f"Enter the grade of student {i+1}: "))
    total_grade += grade

# Calculate the average grade
average_grade = total_grade / num_students

# Display the average grade to the user
print(f"The average grade of {num_students} students is {average_grade:.2f}")

Output

Enter the number of students: 4
Enter the grade of student 1: 80
Enter the grade of student 2: 34
Enter the grade of student 3: 98
Enter the grade of student 4: 78
The average grade of 4 students is 72.50

First, we used the input() function to request the user’s input regarding the number of students in the class.

Which we converted to an integer using the int() function.

We then initialized a variable to store the sum of grades and named it total_grade.

Then, we prompted the user for each student’s grade

which we added to the total_grade variable using a for loop.

We used i variable to show the student’s number as we generated a range of numbers from 0 to num_students-1 using the range() function.

After that, we determined the average grade by dividing the total_grade by the num_students.

The user will then see the average grade displayed using the print() function.

We displayed the average_grade in two decimal places using the format specifier(.2f).

Practice Problem 27: Advanced List Programs In Python For Practice

Problem: A bookshop has a collection of books with their titles, authors, and prices. Write a program to display the books in the bookshop with their details, sorted by the author’s name.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Define a list of books with their details
books = [
    {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "price": 12.99},
    {"title": "To Kill a Mockingbird", "author": "Harper Lee", "price": 9.99},
    {"title": "1984", "author": "George Orwell", "price": 11.99},
    {"title": "Animal Farm", "author": "George Orwell", "price": 8.99},
    {"title": "Pride and Prejudice", "author": "Jane Austen", "price": 7.99},
]

# Sort the books by author's name
books.sort(key=lambda x: x["author"])

# Display the books with their details
for book in books:
    print(f"Title: {book['title']}, Author: {book['author']}, Price: ${book['price']:.2f}")

Output

Title: The Great Gatsby, Author: F. Scott Fitzgerald, Price: $12.99
Title: 1984, Author: George Orwell, Price: $11.99
Title: Animal Farm, Author: George Orwell, Price: $8.99
Title: To Kill a Mockingbird, Author: Harper Lee, Price: $9.99
Title: Pride and Prejudice, Author: Jane Austen, Price: $7.99

Explanation

We define a list of books in this program along with information about each one, such as the author, title, and price.

Then, we arranged the books in alphabetical order by author’s name using the sort() method.

After that, we extracted the author’s name from each book dictionary using the “author” key by a lambda function.

We passed this function as a key argument to the sort() method.

Then, we used the print() function to display each book’s details, including its title, author, and price, using a for loop that iterates through the sorted list of books.

Finally, we formatted the values from each book dictionary into the output using f-strings.

Practice Problem 28: Advanced List Programs In Python For Practice

Problem: A hospital needs to keep track of the number of patients they have treated in a day, along with their symptoms. Write a program to take the symptoms of each patient as input and store them in a list. Then, display the number of patients with each symptom.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Initialize an empty list to store the symptoms
symptoms_list = []

# Ask the user for the symptoms of each patient and add them to the list
while True:
    symptoms = input("Enter the symptoms of the patient (or 'q' to quit): ")
    if symptoms == "q":
        break
    symptoms_list.append(symptoms)

# Count the number of patients with each symptom
symptoms_count = {}
for symptom in symptoms_list:
    if symptom in symptoms_count:
        symptoms_count[symptom] += 1
    else:
        symptoms_count[symptom] = 1

# Display the number of patients with each symptom
for symptom, count in symptoms_count.items():
    print(f"{symptom}: {count}")

Output

Enter the symptoms of the patient (or ‘q’ to quit): rednes
Enter the symptoms of the patient (or ‘q’ to quit): fever
Enter the symptoms of the patient (or ‘q’ to quit): cold
Enter the symptoms of the patient (or ‘q’ to quit): cough
Enter the symptoms of the patient (or ‘q’ to quit): fever
Enter the symptoms of the patient (or ‘q’ to quit): fever
Enter the symptoms of the patient (or ‘q’ to quit): flu
Enter the symptoms of the patient (or ‘q’ to quit): q
rednes: 1
fever: 3
cold: 1
cough: 1
flu: 1

To store the symptoms of each patient in this program, we initialize an empty list called symptoms_list.

The user is prompted for each patient’s symptoms, which are then added to the list using a while loop.

We also give users the option to enter q to end the loop.

After gathering all the symptoms, we use a dictionary function called symptoms_count to determine how many patients have each symptom.

We iterate through the symptoms_list using a for loop,

and for each symptom, we determine whether it already appears in the symptoms_count dictionary.

If it does, we add a new key-value pair to the dictionary with a count of 1.

Otherwise, we decrement the count by 1.

Finally, we iterate through the symptoms_count dictionary using another for a loop.

And then use the print() function to display the number of patients who have each symptom.

The values from the symptoms_count dictionary are formatted into the output using f-strings.

Practice Problem 29: Advanced List Programs In Python For Practice

Problem: A restaurant has a menu with various dishes and their prices. Write a program to take orders from customers and calculate the total bill. Display the bill to the customer.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Define a dictionary of menu items and their prices
menu = {
    "pizza": 12.99,
    "burger": 8.99,
    "sandwich": 6.99,
    "fries": 3.99,
    "salad": 5.99,
    "drink": 2.99,
}

# Initialize the total bill to 0
total_bill = 0

# Ask the user for their orders and calculate the total bill
while True:
    order = input("Enter the order (or 'q' to quit): ")
    if order == "q":
        break
    if order in menu:
        total_bill += menu[order]
    else:
        print("Invalid order")

# Display the total bill to the customer
print(f"Total bill: ${total_bill:.2f}")

Output

Enter the order (or ‘q’ to quit): pizza
Enter the order (or ‘q’ to quit): burger
Enter the order (or ‘q’ to quit): fries
Enter the order (or ‘q’ to quit): q
Total bill: $25.97

Explanation

We define a dictionary menu of menu items and their prices in this program.

Using a while loop, we ask the user for their orders and compute the total bill after setting the total bill’s initial value to 0.

We also give users the option to enter q to end the loop.

We look up every order to see if it is listed in the menu dictionary.

If so, we update the total_bill variable with the item’s cost.

If it doesn’t, a message with an error is shown.

Then, we used the print() function to show the customer the total bill after we have collected all of the orders.

To format the output with the value of the total_bill variable, we used an f-string.

Practice Problem 30: Advanced List Programs In Python For Practice

Problem: A movie theatre needs to keep track of the number of tickets sold for each movie. Write a program to take the name of the movie and the number of tickets sold as input and store it in a list. Then, display the total number of tickets sold for each movie.

Give it a try on our free Online Python Compiler before moving to the solution.

Solution

# Initialize an empty list to store the movies and their ticket sales
movies = []

# Ask the user for the name of the movie and the number of tickets sold
while True:
    movie_name = input("Enter the name of the movie (or 'q' to quit): ")
    if movie_name == "q":
        break
    tickets_sold = int(input("Enter the number of tickets sold: "))
    movies.append((movie_name, tickets_sold))

# Create a dictionary to store the total ticket sales for each movie
ticket_sales = {}
for movie, tickets in movies:
    if movie in ticket_sales:
        ticket_sales[movie] += tickets
    else:
        ticket_sales[movie] = tickets

# Display the total ticket sales for each movie
for movie, sales in ticket_sales.items():
    print(f"{movie}: {sales} tickets sold")

Output

Enter the name of the movie (or ‘q’ to quit): The Future
Enter the number of tickets sold: 1231
Enter the name of the movie (or ‘q’ to quit): The Past
Enter the number of tickets sold: 9
Enter the name of the movie (or ‘q’ to quit): q
The Future: 1231 tickets sold
The Past: 9 tickets sold

Explanation

We stored the name of the movie and the number of tickets sold for each movie by initializing an empty list of movies.

To ask the user for the title of the movie and the number of tickets sold, we used a while loop.

We also give users the option to enter q to end the loop.

Using the int() function, we convert the input for tickets_sold to an integer.

Once we gather all the films and their ticket sales.

We create a dictionary called ticket_sales to hold the total number of tickets sold for each film.

We iterate through the list of movies using a for loop.

And for each movie, we determine whether it is already listed in the dictionary for ticket sales. I

f so, the number of tickets sold is added to the overall revenue for that film.

If not, we add a new key-value pair with the value “number of tickets sold” to the dictionary.

The total number of tickets sold for each film is then displayed using the print() function after using another for loop to iterate over the ticket_sales dictionary.

To format the output using the values from the ticket_sales, we used f-strings.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x