Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
ists are versatile data structures that allow you to store multiple items in a single variable, making them crucial for handling dynamic data. In this article, we'll explore various operations you can perform on lists, such as adding, removing, slicing, and modifying elements.
In Python, a list is a type of data structure that enables users to store information in sequence to constitute a record. Its indexing starts from 0; a list can keep any data (integer, character, boolean, string). Before we jump to Python list operations, it is recommended you go through the python data types. Let us discuss the characteristics of a list.
Operations on Lists in Python
A list in Python is built using square brackets. We write the values inside the square brackets separated by commas.
Create a Python List
Python
Python
#Creating an empty list new_list = []
#List with string new_list=['Coding', 'Ninjas']
You can also try this code with Online Python Compiler
If suppose there is a Python list that has more than one element and the user wants to access a particular element from that list, then that can be done by just declaring that index in square brackets “[ ]”. As we know, indexing starts at 0, so to access the first element of a list, we need to input 0 into the square brackets, and so on for subsequent elements.
Example:
Python
Python
coding_list = ["coding", "ninjas", "data", "science"] #This is a list declared under name: coding_list print(coding_list[1]) #Accessing the 2nd element (index 1) of the list
You can also try this code with Online Python Compiler
Python Lists and Strings allow element accessibility from the end as well, without writing any long codes. If there is a long list with an enormous number of elements and the user wants to access an element that is positioned in the last indexes, rather than traversing the whole list from the start (index 0), the user can simply access the last elements by declaring the index with the “-” sign, which indicates negation.
Example:
Python
Python
coding_list = ["coding", "ninjas", "data", "science"] #This is a list declared under name: coding_list print(coding_list[-2]) #Accessing the 2nd last element (index 3) of the list
You can also try this code with Online Python Compiler
Below are some of the commonly used list operations in python:
1. Append()
As we know, a list is mutable. We can add an element at the back of the list using an inbuilt function of Python list operation append(). Let us see implementations of it.
Python
Python
my_list=[1,2,3] my_list.append(9) my_list.append(8) print("The list after append() operation is: ",my_list)
You can also try this code with Online Python Compiler
In this function, the first input is the position at which the element is to be added, and the second input is the element's value. Here after using the insert() we have added 30 at 5th position in my_list. Hence the updated list will be:
4. remove()
The way we added an element between the list, similarly, we can remove from in between a list using an inbuilt Python list operation function remove().
Python
Python
my_list.remove(10) print("The list after remove() operator is: \n",my_list)
You can also try this code with Online Python Compiler
After using pop() operator, the last element would be removed from our my_list list. Here the last element, 5, is removed from the list. Hence our updated list is
6. Slice()
This method is used to print a section of the list. Which means we can display elements of a specific index.
Python
Python
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])
You can also try this code with Online Python Compiler
Using the slicing operator, we have sliced elements from range of 3 to 12 in the my_list. Hence the above code would print elements whose index lies between the range 3 to 12.
Note that the slice method only prints the elements; it does not change the list.
7. reverse()
To reverse the indexing of elements in a list, the simple built-in function reverse() can be used. This function allows the user to reverse the order of elements very quickly and without large code lines. To reverse a list, it needs to be parsed with the function itself.
Other Python list operations are len(), min(), and max(). As the name suggests, they are used to know the length of a list, the minimum element in the list, and the maximum element in the list, respectively.
Python
Python
print("Length of the list is: ",len(my_list)) print("Maximum element in the list is: ",max(my_list)) print("Minimum element in the list is: ",min(my_list))
You can also try this code with Online Python Compiler
After using the extend() and count() operator on my_list, the the number of repetitions of 21 are:
Here 2 shows the number of occurrences of element 23.
10. Concatenate
Concatenate is a very simple process, with the literal meaning of combining or joining two objects. Similarly, concatenation in Python can be used to combine two lists or strings. Concatenation in Python can be simply performed by using “+” between variable names that hold a string or list.
Did you know that you can increase the number of elements in a list by simply multiplying it by a number? For example, by multiplying a list with the number ‘n’, you get that list element being repeated ‘n’ times. List multiplication can be performed by just using the “*” operator. Following is a code example:
Example:
Python
Python
list_one = [100, 150, 200] list_two = list_one * 3 #Multiplied the list with 3 print(list_two)
You can also try this code with Online Python Compiler
index() is a built-in Python function that lets users access the elements of a list, tuple, or string. This is a really useful function, especially when the data inside the list or tuple is very large. Note that if there are duplicate entries in the list, tuple, or string, then the first occurrence of that particular element will be represented in the output.
Example:
Python
Python
list_one = [100, 150, 200] print(list_one.index(100)) #Using index function for a list
You can also try this code with Online Python Compiler
So far, we've seen various Python list operations using inbuilt functions. Now let us look at some arithmetic and logical operations in lists.
14. clear()
If you want to clear all the elements present in a list, set, or dictionary, then clear() is one of the most efficient and easy built-in functions to use. It is important to note that this can be implemented on a list, set, or dictionary only. Using this function, you can clear all the contents, and the result is None.
Example:
Python
Python
list_one = [100, 150, 200] list_one.clear() #This clears all the elements present in the list print(list_one)
You can also try this code with Online Python Compiler
List Comprehension is one of Python’s most efficient ways to work on a list and implement conditions on a list, all in just one line! The list comprehension expression mainly consists of a command, an iterable variable, and the condition to be implied. It is a highly useful technique to decrease code lines and make the codebase more accessible.
Example
Python
Python
list_one = [100, 150, 200, 250, 300] list_cubic = [number ** 3 for number in list_one] #This line generates a list with cubes of all elements in the list_one print(list_cubic)
You can also try this code with Online Python Compiler
In the code above, number ** 3 is the expression or command, and number is the iterable variable in that list.
Output:
Frequently Asked Questions
What are the characteristics of a Python list?
Python lists are ordered, mutable collections that can store elements of different types. Lists allow indexing, slicing, and support various operations like adding, removing, or modifying items. They can grow or shrink dynamically as elements are added or removed.
What are the key differences between Python lists and dictionaries?
Python lists are ordered collections of elements accessed via indices, while dictionaries are unordered collections of key-value pairs, where data is accessed using unique keys. Lists support duplicates, but dictionary keys must be unique.
What is the difference between a list and a tuple in Python?
The primary difference is that lists are mutable, meaning elements can be changed, added, or removed, while tuples are immutable, meaning they cannot be modified after creation. Tuples are generally faster and are used for fixed data.
What is the fastest type of list in Python?
Lists with a time complexity of O(1) are considered to be the fastest, other than that, lists generated using external libraries like NumPy are considered to be highly efficient as they can store multidimensional arrays.
Conclusion
In this article, we explored various Python list operations, covering built-in functions, arithmetic, and logical operators that can be applied to lists. We also discussed how these functions and operators work, providing detailed implementations for better understanding and practical use.