Python Lists Practice Programs For Beginners
Test your Python Lists knowledge with practice programs! In this blog, we will solve 12 python lists exercises for beginners.
The Python list object is the most general mutable sequence type provided by the language. Python lists are mutable, that is the contents of the list be modified in place. You can change a list in place, add new elements, overwrite existing elements or delete them as well. Also, note that in a list, the same value can occur more than once. Alright! Here are simple programs based on Lists that will help you get started with Lists in Python.
Remember to tackle these questions on your own before checking for solutions!
- Find the Smallest and the Largest List Elements on Inputs Provided by the User
- Split a List in Half and Store the Elements in Two Different Lists
- Remove Multiple Empty Strings From a List of Strings
- Interchange First and Last Elements of in a List
- Print Elements With Frequency Greater Than a Given Value k
- Find All Possible Combinations of a List With Three Elements
- Square Each Element of the List and Print List in Reverse Order
- Remove All Occurrences of an Element From a Given List
- Remove Empty List From a Given List
- Remove Negative Values From a List With Filter() Function
- Create a Flat List Out of a Given List of Lists Using Built-in Function
- Count and Filter Odd and Even Numbers of Given List Using Loops
Write a Program in Python to Find the Smallest and the Largest List Elements on Inputs Provided by the User
You can use the built-in functions to find the max and min of the list. Before that, prompt the user to enter the size of the list and the list items. Then by using the append() method inside the loop populate an initially empty list.
#find the smallest and largest elements of a list # creating an empty list res_list = [] # prompting for the number of elements num = int(input("How many elements in list? :")) #loop to append each element entered by user to res_list for x in range(num): numbers = int(input('Enter number ')) res_list.append(numbers) print("\nMaximum element in the list is :", max(res_list)) print("Minimum element in the list is :", min(res_list))
Best-suited Python courses for you
Learn Python with these high-rated online courses
Write a Python Program to Split a List in Half and Store the Elements in Two Different Lists
There are multiple ways to split a given list into half and print two halves as separate Python lists. Let us look at various methods.
Using List Slicing
Slicing is basically a generalized form of indexing that returns an entire section in a single step, instead of a single item. We can use that to achieve what we want as shown below.
#using list slicing to split the list to half List1 = [1,'ABC', 2, 3, 'abc', 'XYZ', 4] #offset of middle element is 2 print("The first half of the list", List1[:3]) print("The second half of the list", List1[3:])
Using islice() Function
As the name indicates, the islice(iterable, start, stop, step) function allows you to iterate through the lists and fetch a part of the iterable based on the parameters ‘start’, ‘stop’, and ‘step’ given by the user.
#using islice() to split the list to half from itertools import islice List1 = [1,'ABC', 2, 3, 'abc', 'XYZ', 4] length_to_split = [len(List1)//2]*2 print(length_to_split) iterable_lst = iter(List1) res_list = [list(islice(iterable_lst, elem)) for elem in length_to_split] print("Initial list:", List1) print("List halves after splitting", res_list)
Write a Python Program to Remove Multiple Empty Strings From a List of Strings
Dealing with empty strings when working with huge amounts of data can be a tedious task. So, if these empty strings are not contributing to anything, how to remove them? This can be done in a couple of ways.
Using remove()
Iterate through the list, check for empty strings and remove them using remove() method as shown below.
#Using remove() List1 = ['','ABC','xyz', '', 'abc', 'XYZ'] print("Original List:", str(List1)) #iterate & remove ''strings while("" in List1) : List1.remove("") #updated list print("List after removing empty strings:", str(List1))
Using List Comprehension
#Using list comprehension List1 = ['','ABC','xyz', '', 'abc', 'XYZ'] print("Original List:", str(List1)) #list comprehension List1 = [x for x in List1 if x] #updated list print("List after removing empty strings:", str(List1))
Go ahead and try achieving this using various other techniques.
Write a Python Program to Interchange First and Last Elements of in a List
That should be simple right? There are literally multiple ways to implement this. Here’s one of them.
Using Indexing
#swapping first & last items of a list - using indexing List1 = ['XYZ', 'ABC', 'xyz', 'abc'] print("Original List:", str(List1)) List1[0], List1[-1] = List1[-1], List1[0] #updated list print("List after swapping:", str(List1))
Write a Program in Python to Print Elements With Frequency Greater Than a Given Value k
You just need to iterate through the list and count the frequency of each element. If the frequency (or count) is greater than the given value k, then add that element to the new list (initially empty). You can implement this using the regular loops and count() method, which returns the count of elements passed as an argument.
#get list items with frequency greater than k List1 = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 5, 5, 5, 6, 7] k = 2 print("Original List:", str(List1)) #creating empty list res_list = [] #iterating through list count #and add the item to new list if count > k for i in List1: counter = List1.count(i) if counter > k and i not in res_list: res_list.append(i) print("The list items with count > k = ", res_list)
Write a Python Program to Find All Possible Combinations of a List With Three Elements
One way to achieve this is using an in-built function, itertools.permutations(). This method returns all possible arrangements for a given iterable and all the items of the iterable are considered to be unique based on their position. You can use this method to find combinations of any number of elements.
#Find all possible combinations from itertools import permutations List3 = ['A', 'B', 'C'] possible_combi = permutations(List3, 3) #counter to keep the track of no of combinations count = 0 for i in possible_combi: count = count + 1 print(i) print("The total number of combinations are:", count)
Without using any built-in method: Naive Method
#Find all possible combinations using loops def possible_arrangments(list1): for x in range(3): for y in range(3): for z in range(3): # check if the indexes are not # same if (x!=y and y!=z and x!=z): print(list1[x], list1[y], list1[z]) # Driver Code List3 = ['A', 'B', 'C'] possible_arrangments(List3)
Write a Python Program to Square Each Element of the List and Print List in Reverse Order
This can be implemented very easily if you are aware of basic list methods. In the solution below, I have used list comprehension to iterate through the list and square each element. Finally I reversed the list in-place using reverse() method.
#square each element & reverse the list List1 = [1, 2, 3, 4, 5] print("Original List:", str(List1)) #using list comprehension to iterate the list #calculate square of each item List1 = [num*num for num in List1] print("Squared List:", str(List1)) #reversing the list in place List1.reverse() print('Final List:', str(List1))
Write a Python Program to Remove All Occurrences of an Element From a Given List
Given a list, the task is to remove all the occurrences of a particular element from the list. You can do this in multiple ways.
Using remove() method
Just iterate through the list and use remove() function to delete all occurrences very easily.
#Remove All Occurrences of an Element List1 = [22, 24, 30, 22, 45, 67, 22, 30, 45] item_to_remove = 22 print("The original list is : " + str(List1)) #function to remove all occurances def remove_an_item(test_list, value): # remove the item for all its occurrences for x in test_list: if(x == value): test_list.remove(x) return test_list # calling the function remove_items() res_list = remove_an_item(List1, item_to_remove) # updated list after removing 22 print("Updated list after remove operation: " + str(res_list))
Using List Comprehension
#Remove All Occurrences of an Element using List Comprehension List1 = [22, 24, 30, 22, 45, 67, 22, 30, 45] item_to_remove = 22 print("The original list is : " + str(List1)) #function to remove all occurances def remove_an_item(test_list, value): # remove the item for all its occurrences new_list = [x for x in test_list if x != value] return new_list # calling the function remove_items() res_list = remove_an_item(List1, item_to_remove) # updated list after removing 22 print("Updated list after remove operation: " + str(res_list))
Write a Python Program to Remove Empty List From a Given List
More often than not we come across a situation where we have to deal with the empty data like an empty list, empty string, None, etc. In this example, let’s discuss different ways to remove the empty lists from a given list.
Using filter() method
In simple terms, the filter function filters the given iterable by applying a function to each element of the list and checking if it evaluates to true or not. The syntax is
filter(function, iterable)
#remove empty lists from a list using filter() List1 = ['ABC',[], 'xyz', 'abc',[], 'XYZ', []] print("The original list is : " + str(List1)) res_list = list(filter(None, List1)) # updated list after removing empty lists print("Updated list after remove operation: " + str(res_list))
Using List Comprehension
#remove empty lists from a list using list comprehension List1 = ['ABC',[], 'xyz', 'abc',[], 'XYZ', []] print("The original list is : " + str(List1)) res_list = [x for x in List1 if x != []] # updated list after removing empty lists print("Updated list after remove operation: " + str(res_list))
Write a Python Program to Create a Flat List Out of a Given List of Python Lists Using Built-in Function
As you might already know, a list can have elements of any type of element and that includes other lists. So, you can have a list within a list called a nested list or a two-dimensional list. Flattening a list means converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists.
Example: [[1, 2, 3], [4, 5], [6, 7, 8]]
Output: [1, 2, 3, 4, 5, 6, 7, 8]
You can flatten a list in multiple ways: using list comprehension, using loops, recursion, built-in functions, etc. This example demonstrates a few of them.,
Using Loops – Most Basic Way
#create a flat list from list of lists - Using loops List1 = [[1, 2, 3], ['x', 'y', 'z'], ['A', 'B', 'C']] print("The original list is : " + str(List1)) #empty list flat_list = [] #iterating over list of list for x in List1: flat_list = flat_list + x #updated flat list print("Flat list" + str(flat_list))
Using List Comprehension
#create a flat list from list of lists - Using list comprehension List1 = [[1, 2, 3], ['x', 'y', 'z'], ['A', 'B', 'C']] print("The original list is : " + str(List1)) #empty list flat_list = [x for sublist in List1 for x in sublist] #updated flat list print("Flat list" + str(flat_list))
Using chain() method from itertools module
This chain() method iterates through each consecutive sub-sequences until there are no more sub-sequences. It returns an iterable that you might have to convert to a list if it is not a list.
#create a flat list from list of lists - Using chain() method from itertools import chain List1 = [[1, 2, 3], ['x', 'y', 'z'], ['A', 'B', 'C']] print("The original list is : " + str(List1)) #empty list flat_list = list(chain(*List1)) #updated flat list print("Flat list" + str(flat_list))
Write a Python Program to Remove Negative Values From a List With Filter() Function
The filter function filters the given iterable by applying a function to each element of the list and checking if it evaluates to true or not. The syntax is filter(function, iterable). You can use a lambda function to evaluate if the elements of the list are positive or negative as shown below.
#remove -ve elements using filter() List1 = [10, 50, -40, 60, -30] print("The original list is : " + str(List1)) res_list = list(filter(lambda x : x > 0, List1)) #list with positive values print("Updated list" + str(res_list ))
Write a Python Program to Count and Filter Odd and Even Numbers of Given List Using Loops
There are multiple ways to filter out odd and even elements from a given list, such as loops, list comprehensions, using lambda expressions, etc. In this example, I am demonstrating how to achieve this using a for loop.
#count for odd & even numbers using while loop List1 = [10, 5, -4, 6, -3, 7, 9] print("The original list is : " + str(List1)) def find_odd(test_list): counter = 0 odd_list = [] # using while loop for num in List1: if num % 2 != 0: odd_list.append(num) counter += 1 print("The odd number list =", odd_list) print("The number of odd elements are:", counter) def find_even(test_list): counter = 0 even_list = [] # using while loop for num in List1: if num % 2 == 0: even_list.append(num) counter += 1 print("The odd number list =", even_list) print("The number of odd elements are:", counter) find_odd(List1) find_even(List1)
That’s it, folks! I hope you found these Python programs helpful. If you have any problem statement that you are stuck with please raise a query in the comment section below. Happy coding!
Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions
Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.
Click here to submit its review with Shiksha Online.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio