Basic operations in Python lists

Python is one of the most popular programming languages. Due to its powerfulness and easy-to-use simple syntax, it has attracted many programmers worldwide to adopt and be a part of the community. Python is the main language in many fields like Machine Learning, Data Science, Web Application, Scientific Programming, etc. There is also a huge python community on the web, such as in stack overflow, that helps us fix bugs easily. In Codeunderscored, we provide helpful and informative tutorials on python and also other languages. To see all the articles on python, go to our python tutorials section.

In this tutorial, we will learn to perform some basic operations on python lists such as sorting, calculating the length of a list, etc. To follow this tutorial, python should be installed on your computer so you can try each of the codes by writing it on your own. It is also recommended to use an IDE(Integrated Development Environment) such as the open-source Visual Studio Code for writing programs fast and efficiently. Now, let us start our tutorial with the introduction of python lists.

Introduction

Lists are one of the most important data types in python. They are similar to the Arrays in C++ and javascript. Python lists can be used to store any type of data sequentially. The condition for creating a python list is that the data must be separated by commas, and the list should be enclosed by box brackets [ ]. An example of a python list is shown below.

list1 = [1, 2, 3, 4, 5, 6, 7, 100]

In the above example, we created a python list and stored some random integers in it. However, it is not necessary to create a list containing only integers. We can also create a list and store other data types like strings, float in it. To learn more about python lists, you can refer to our tutorial on the basics of python lists. Now let us see some of the basic operations on Python lists.

Basics Operations on python Lists

Many operations can be performed using python lists. Some of the important operations will be discussed here. All the operations will be explained with an example code, and also alternative ways will be discussed to perform the same operation. The following operations will be discussed in this tutorial, calculating the length, sorting, reversing, calculating the min and max of the list, counting the occurrence of an element in the list, Merging lists, Adding elements to the list, and removing elements from the list.

Let us see each of the operations one by one.

Finding the length

We can calculate the length of a list in python by using two methods: the len() function of python and the second method by using the for loop of python. Let us discuss each of the methods one by one.

Using len() function

In python, there is a built-in function len() that can be used to calculate the length of a python object. The len() function is used to calculate the length of a python object by passing it in the function’s argument, and it will return the length of the string. This function can be used with python objects such as lists, strings, tuples. For example, to calculate the length of a list using the len() function, we need to pass the list as an argument to the len() function, and the function will return the length of the list as an integer.

# Creating the python list
list1 = [1, 2, 3, 4, 5]
# Displaying the list
print("[+] Given list ", list1)
# Calculating the length of the list
length = len(list1)
# Displaying the length of the list
print(f"[+] The length of the list is : {length}")

In the above program, we created a python list containing some integers and displayed the list in the console using the print() function. Next, we pass the list into the len() function as an argument, and we displayed the value return by the len() function in the console using the print() function. On running the above code, we will get the output as shown in the below image.

Python program to calculate the length of a list using the len() function
Python program to calculate the length of a list using the len() function
Using python for loop

The length of a python list can also be calculated using for loop. To achieve this, we need to iterate over each element of the list and increment a variable count by one for each iteration. The following code shows an illustration of this method.

# Creating the python list
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
# Displaying the list
print("[+] Given list ", list1)
# Calculating the length of the list
count = 0
for i in list1:
    count = count + 1 
# Displaying the length of the list
print(f"[+] The length of the list is : {count}")

In the above code, we created a python list containing 10 integers and display it to the console using the print() function. Next, we created a variable with the name count and then initialized the count variable with 0. Finally, we use the for loop of python to iterate on each element of the list and increment the value of count by one for each iteration. After the complete iteration of the for loop, the count variable will contain the length of the list. On running the above code, we will get the output as shown in the below image.

python program to calculate the length of a list using for loop
python program to calculate the length of a list using for loop

Sorting

Python lists can be sorted very easily. There are two ways to sort a python list. One is by using the built-in sort() method of python lists, and the second is by using the built-in sorted() function of python. Let us discuss both of them one by one.

Using sort() method

Python list has a built-in sort() method that can be used to sort a python list. This method also accepts an optional parameter named reverse that can be set to true or false. By default, the sort() method will sort the list in ascending order, but we can also sort it in descending by using the parameter reverse=True in the sort() method. The below example code shows a simple demonstration of the sort() method.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 80, 60, 70]
# Displaying the Python list
print(" [+] Given list ", list1)
# Sorting the python list in ascending order
list1.sort()
# Displaying the sorted list
print(" [+] Ascending order", list1)
# Sorting the python list in descinding order
list1.sort(reverse=True)
# Displaying the sorted list
print(" [+] Descending order", list1)

In the above code, we first created a python list containing some integers and displayed the list in the terminal using the print() function. Next, we use the sort() method of the python list without any argument, so it sorts the list in ascending order, and we displayed the sorted list using the print() function. We again use the sort() method on the list with the parameter reverse=True in the argument. Thus, the list will be sorted in descending order. Then we displayed the sorted list using the print() function. On running the above code, we will get the output as shown in the below image.

Python program to sort a list using the sort() method
Python program to sort a list using the sort() method
Using sorted() function

In python, we have a sorted() function that can be used to sort some python objects. It is used to sort objects like lists, tuples, strings, etc. First, we need to pass the object as an argument to the sorted() function. By default, the sorted() function will sort a list in ascending order, but we can change it by using an optional parameter reverse=True by using which will sort the list in descending order. The sort() method changes the value of the original list by sorting it, but the sorted() function does not change the original list. It just returns the sorted list of the original list without manipulating the value of the original list. The following code block shows a practical demo of the sorted() function.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 80, 60, 70]
# Displaying the Python list
print(" [+] Given list ", list1)
# Sorting the python list in ascending order
list2 = sorted(list1)
# Displaying the sorted list
print(" [+] Ascending order", list2)
# Sorting the python list in descinding order
list3 = sorted(list1, reverse=True)
# Displaying the sorted list
print(" [+] Descending order", list3)

In the above code, we first created a python list and displayed the list to the console using the print() function. Next, we used the sorted() function and passed the python list as an argument to it. The function will return the list by sorting it in ascending order. Next, the return sorted list is stored into a variable and displayed using the print() function. Again, the sorted() function is called, and we pass the list and the parameter reverse=True in its argument, now the list will be sorted in descending order. Next, we use the print() function to display the sorted list. On running the above code, we will get the output as shown in the below image.

python program to sort a list using the sorted() function
python program to sort a list using the sorted() function

If you want to learn more about performing sorting in python lists, you can refer to our tutorial on sorting python lists that will give you complete detail on sorting a list in python.

Reversing

We have seen how to sort a python list. Now let us see how we can reverse a python list. There is a built-in function reverse() that can be used to reverse a python list in python. We can also use python’s for loop to reverse a list. Both the methods were discussed in detail below.

Using reverse() method

Python list has a built-in reverse() method that can be used to reverse a list easily. The below code shows a demo of using the reverse() method to reverse a list.

# creating a pthon list containing some integers
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("[+] The Original list is : ", list1)
# reversing the list using the reverse method
list1.reverse()
print("[+] The reversed list is : ", list1)

We created a python list in the above code and displayed it using the print() function. Then, we use the reverse() method of the list that will reverse the original list. At last, we displayed the reverse list by using the print() function. On running the above code, we will get the output as shown in the below image.

python program for Reversing a python list using the reverse method
python program for Reversing a python list using the reverse method
Using for loop

We can also use python for loop to reverse a list. To achieve that, we need to iterate for loop from zero to the length of the list and then add each element from the last into the first of a new list. The following code shows a practical demo of the method.

# creating a pthon list containing some integers
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("[+] The Original list is : ", list1)
n = len(list1)
list2 = []
# reversing the list using the reverse method
for i in range(0, n):
    list2.append(list1[n-1-i])

print("[+] The reversed list is : ", list2)

In the above code, first, we created a python list and displayed it using the print() function. Next, we calculate the length of the list using the len() function, which we have discussed earlier. We also create an empty list to store the reverse list. Next, we used the python for loop to iterate from 0 to the length of the list and used the append() method of the new list to append each element from the end of list1 into list2 for each iteration. At last, we displayed the list2 using the print() function. On running the above code, we will get the output as shown in the below image.

Python program to reverse a list using for loop
Python program to reverse a list using for loop

Adding elements

Adding elements to a list can be done using three methods of python lists. The first is the insert() method, which accepts the index and the element as an argument for inserting the element at the index. The second method is append() which accepts an element as an argument and adds it to the end of the list. The third method is the extend() it accepts an iterable as its argument and adds each of the elements of the iterable to the list. Thus, we have a step-by-step guide that gives complete detail on adding elements to a list in python.

Removing elements

We also need to remove elements from a python list. To do this, we have several functions and methods in python. We will discuss three of the methods here. The first is the remove() method of the python list. The second is using the pop() method of list. The third one is by using the clear() method.

Using remove() method

Python lists have a built-in remove() method that can be used to remove an element from the list. The remove() method accepts the element that we want to remove as its argument. The following program shows how to use the remove() method.

# creating a pthon list containing some integers
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("[+] Before Removing : ", list1)
# removing 50 from the list using the remove method
list1.remove(50)
print("[+] After Removing : ", list1)

In the above program, first, we created a list containing some integers and displayed it using the print function. Next, we use the remove method of the list with the argument 50, so it will remove element 50 from the list. At last, we displayed the final list using the print() function. On running the program, we will get the following output.

Python program to remove an element from a list using the remove() method
Python program to remove an element from a list using the remove() method
pop()

The pop() method of the python list can be used to remove one element from the list. It accepts the index of the element that we want to remove as its argument. It removes the element from the list and returns the element that it has removed. The following code gives an illustration of the method.

# creating a pthon list containing some integers
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("[+] Before Removing : ", list1)
# removing 9th index element from the list using the pop method
num = list1.pop(9)
print("[+] After Removing : ", list1)
print("[+] Element that removed : ", num)

We first created a python list containing some integers on the above code and displayed it using the print() function. Then we used the pop method of the list to remove the element with the index 9 and get the number that is returned. Next, we print the list and the number that has been removed using the print() function. On running the above code, we will get the following output.

python program to remove an element from a list using the pop() method by passing index in argument
python program to remove an element from a list using the pop() method by passing index in the argument
clear()

The clear() method can be used to clear the full list. It accepts no argument, and it will empty the full list. The following program shows a practical demo of this method.

# creating a pthon list containing some integers
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("[+] Before Removing : ", list1)
# Empties the list using the clear method
list1.clear()
print("[+] After Removing : ", list1)

In the above code, we first created a python list containing some integers and displayed it using the print() function. Next, we use the clear() method of the list that empties the list, and we print the list again. On running the above code, we will get the following output.

Removing all the element of a list by using the clear() method
Removing all the elements of a list by using the clear() method

Min and Max value of a list

Sometimes we need to find the minimum and maximum value of a python list. Python provides two functions, min() and max(), that can be used to find the minimum and maximum value of a list. We can also find the minimum and maximum values by using a different technique. Let us see some details on the methods.

Using max() and min() function

Python provides min() and max() functions that can be used to get the minimum and maximum value respectively of a python list. This function can also be used on some other objects like tuples. The accept the python object as an input and return the minimum and maximum value as an integer. The following code shows a demonstration of how to use them.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 80, 60, 70]
# Displaying the Python list
print("[+] Given list ", list1)
# Getting the maximum value of the list
ma = max(list1)
print("[+] The Maximum of the list is : ", ma)
# Getting the minimum value of the list
mi = min(list1)
print("[+] The Minimum of the list is : ", mi)

In the first line of the above code, we have created a python list containing some integers, and we printed the list using the print() function. Next, we use the max() function and pass the list as an argument to it. The max function returns the maximum value of the list, and we displayed the maximum value using the print() function. Next, we use the min() function and pass the list to it and get the minimum value in return, and we displayed the minimum value using the print() function. On running the above code, we will get the following output.

Calculating minimum and maximum value of a list using the min() and max() function
Calculating minimum and maximum value of a list using the min() and max() function
Using for loop

We can also calculate the maximum value of a loop using the for loop of python. To achieve this, we need to iterate over the loop elements and choose the largest one. The below code shows a practical demonstration of how to use this method.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 80, 60, 70]
# Displaying the Python list
print("[+] Given list ", list1)
# Getting the maximum value of the list

m = 0
for i in list1:
    if i>m:
        m=i

print("[+] The Maximum value of the list is : ", m)

On the above code, First, we created a list containing integers and displayed it using the print() function. Then we initialize a variable m with zero. Next, we use the for loop and iterate over the elements of the list. For each element, we check if it is greater than m them the value will be assigned to m. After the completion of the loop, m will contain the largest number of the list. At last, we displayed it using the print() function. On running the above code, we will get output as shown in the below image.

Calculating minimum and maximum value of a list without using the min() and max() function
Calculating minimum and maximum value of a list without using the min() and max() function
Other Method(Sorting and getting the first and last element)

In this method, we will first sort the list using the sort() method of python, then the first and the last element of the list are the minimum and maximum values, respectively. The below code shows a practical illustration of this method.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 80, 60, 70]
# Displaying the Python list
print("[+] Given list ", list1)
list1.sort()
# Getting the maximum value of the list
ma = list1[-1]
print("[+] The Maximum value of the list is : ", ma)
# Getting the minimum value of the list
mi = list1[0]
print("[+] The Minimum value of the list is : ", mi)

In the above code, first, we created a python list containing some integers and displayed the list in the terminal using the print() function. Next, we sort the original list in ascending order using the sort() method of the python list. Then, we access the last element of the list by using negative indexing of the python list. Since the list is sorted in ascending order, the last element will be the maximum of the list. So, we printed the last element, i.e., the maximum value using the print() function. Next, we access the first element of the sorted list using zero indexing. The first element will be the minimum value of the list. So we displayed it using the print() function. On running the above code, we will get the following output.

claculating max and min value
calculating max and min value

Count

Sometimes we need to count the occurrence of an element in a list. We can achieve this using the count() method of the python list, which accepts the element as an argument and returns its occurrence in the list. We can also use python’s for loop to achieve the same. Let us discuss both methods in detail.

Using Count() method

Python list has a built-in count() method that can count the occurrence of an element in the list. We need to pass the element as an argument to this method, and then it returns an integer containing the total occurrence of the element. The following code shows a practical demonstration of the method.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 50, 60, 70]
# Displaying the Python list
print("[+] Given list ", list1)
# counting the occurence of 50 in the list
c = list1.count(50)
print("[+] The occurence of 50 in the list is :", c)

We first created a list containing integers in the above code and displayed it using the print() function. Then we used the count() method of the list and passed 50 as its argument to count the occurrence of 50 in the list. Next, we displayed the count using the print() function. Finally, on running the code, we will get the output as shown in the below image.

Python progrm to count the number of occurence of an element in a list using the count() method
Python program to count the number of occurrences of an element in a list using the count() method
Using for loop

We can also count the occurrence of an element using the for loop in python. To achieve this, we need to initialize a count variable with zero and then loop through the elements of the list and increment the count variable for every occurrence of the element in the list. The below code shows a practical illustration.

# created a python list
list1 = [30, 20, 10, 50, 50, 40, 100, 50, 60, 70]
# Displaying the Python list
print("[+] Given list ", list1)
#Counting the occurence of 50 in the list
c=0
for i in list1:
    if i == 50:
        c = c + 1
print("[+] The occurence of 50 in the list is :", c)

We first created a python list containing integers on the above code and displayed it using the print() function. Then, we initialize a variable with zero and use the for loop to iterate over the elements of the list. If there are any elements in the list equal to 50, then the count variable will be increment by one. After completing the loop, we will get the number of occurrences of 50 in the list in the count variable. So in the last line of the code, we displayed the count using the print() function. On running the above code, we will get the output as shown in the below image.

python program to count the occurence of an element in a list using for loop
python program to count the occurrence of an element in a list using for loop

Merging lists

In python, the merging of two lists can be done using the addition(+) operator. The + operator is significant in python and can merge many other types of objects like strings, tuples, etc. For example, to merge two lists, list1 and list2, we need to follow the syntax list1 + list2. The + operator can also be used to merge more than two lists. The following code gives a practical demonstration of merging two lists in python.

# Creating three python list containing integers
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
list3 = [9, 10, 11, 12]
# Displying the lists
print("\n[+] Given Lists... \n")
print(list1)
print(list2)
print(list3)
print("\n[+] Merging The Lists... \n")
# Merging the first two list
print(list1 + list2)
# Merging all the three list
print(list1 + list2 + list3)
print("\n[+] Exiting The Program... \n")

In the above program, first, we created three python lists containing integers and displayed all three lists to the console using the print() function. Next, we merged the first two lists using the + operator and displayed the merged list using the print() function. After that, we again used the + operator and merged all three lists, and displayed it using the print() function. On running the above code, we will get the output as shown in the below image.

Python program to merge multiple list into one
Python program to merge multiple lists into one

Conclusion

In this tutorial, we have learned how to perform some basic operations on the python list. We have seen each of the operations with example code, so it will be better to understand. You may also want to see our tutorial on working with dictionaries in python.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *