A Python list serves as a versatile container capable of storing objects of different types. Each element in the list is assigned an index, starting from zero, which allows for easy access and retrieval of specific items. This tutorial will provide you with a comprehensive understanding of Python lists, including their creation, manipulation, and various operations you can perform on them. With practical examples, you’ll quickly grasp how to leverage the power of lists in your Python programs.
Unique Features of Python Lists
Here are some key features of Python lists:
- Ordered Elements: Python lists maintain the order of elements as they are inserted.
- Dynamic Size: Lists can grow or shrink dynamically as elements are added or removed.
- Heterogeneous Elements: Lists can hold different types of data within the same list.
- Mutable: Lists can be modified in place, allowing for changes to individual elements.
- Indexing and Slicing: Lists support accessing specific elements or sublists using indices or slices.
- Iterable: Lists can be iterated over using loops or comprehensions.
- Nesting: Lists can be nested, enabling the creation of complex data structures.
Creating a List in Python
a) The simplest way to create a list is by using the Subscript Operator which is the square brackets [ ]
. It doesn’t require a function call, hence making it the fastest way to create the list. Here are some examples for your reference.
# blank list L1 = [] # list of integers L2 = [10, 20, 30] # List of heterogenous data types L3 = [1, "Hello", 3.4] print(type(L1)) # <class 'list'>
b) Also, you can make use of the list constructor list( )
. Below are some more examples demonstrating the list() method.
theList = list([1,2]) print(theList) # [1, 2]
theList = list([1, 2, [1.1, 2.2]]) print(theList) # [1, 2, [1.1, 2.2]] print(len(theList)) # 3
c) Alternatively, you can think of using Python list comprehension. However, it can be used to create a list based on existing lists. A list comprehension has the following syntax:
#Syntax - How to use List Comprehension theList = [expression(iter) for iter in oldList if filter(iter)]
It has square brackets grouping an expression followed by a for-in clause and zero or more if statements. The result will always be a list. Check out the below example.
listofCountries = ["India","America","England","Germany","Brazil","Vietnam"] firstLetters = [ country[0] for country in listofCountries ] print(firstLetters) # ['I', 'A', 'E', 'G', 'B', 'V']
Creating a Multi-dimensional List
You can create a sequence with a pre-defined size by specifying an initial value for each element.
init_list = [0]*3 print(init_list) # [0, 0, 0]
With the above concept, you can build a two-dimensional list.
two_dim_list = [ [0]*3 ] *3
The above statement works, but Python will only create the references as sublists instead of creating separate objects.
two_dim_list = [ [0]*3 ] *3 print(two_dim_list) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] two_dim_list[0][2] = 1 print(two_dim_list) # [[0, 0, 1], [0, 0, 1], [0, 0, 1]]
Accessing Elements from Python List
The simplest method is to use index operator ([])
to access an element from the list. Since the list has zero as the first index, a list of size ten will have indices from 0 to 9.
Any attempt to access an item beyond this range would result in an IndexError. The index is always an integer. Using any other type of value will lead to TypeError.
Also, note that a Nested list will follow the nested indexing. Let’s take some examples.
vowels = ['a','e','i','o','u'] consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] #Accessing list elements using the index operator print(vowels[0]) # a print(vowels[2]) # i print(vowels[4]) # u #Testing exception if the index is of float type try: vowels[1.0] except Exception as ex: print("Note:", ex) # Note: list indices must be integers or slices, not float #Accessing elements from the nested list alphabets = [vowels, consonants] print(alphabets[0][2]) # i print(alphabets[1][2]) # d
Reverse or Negative Indexing
In Python, you can use negative indexing to access elements in a list in reverse order. Negative indices are used to count positions from the end of the list. Instead of starting with index 0, you start with -1 for the last element, -2 for the second-to-last element, and so on.
vowels = ['a','e','i','o','u'] print(vowels[-1]) # u print(vowels[-3]) # i
Add / Remove Elements from a List
a) You can use the assignment operator (=) to add or update elements in a list.
theList = ['Python', 'C', 'C++', 'Java', 'CSharp'] theList[4] = 'Angular' print(theList) theList[1:4] = ['Ruby', 'TypeScript', 'JavaScript'] print(theList) # ['Python', 'C', 'C++', 'Java', 'Angular'] # ['Python', 'Ruby', 'TypeScript', 'JavaScript', 'Angular']
You can also push one item at the target location by calling the insert() method.
theList = [55, 66] theList.insert(0,33) print(theList) # [33, 55, 66]
b) You can make use of the ‘del’ Python keyword to remove one or more items from a list. Moreover, it is also possible to delete the entire list object.
vowels = ['a','e','i','o','u'] # remove one item del vowels[2] # Result: ['a', 'e', 'o', 'u'] print(vowels) # remove multiple items del vowels[1:3]
c) You can call the remove() method to delete the given element or the pop() method to take out an item from the desired index. The pop() method deletes and sends back the last item in the absence of the index value. That’s how you can define lists as stacks (i.e., FILO – First in, last out model).
vowels = ['a','e','i','o','u'] vowels.remove('a') # Result: ['e', 'i', 'o', 'u'] print(vowels) # Result: 'i' print(vowels.pop(1)) # Result: ['e', 'o', 'u'] print(vowels) # Result: 'u' print(vowels.pop())
Extend / Append to Lists
a) You can extend a list with the help of the arithmetic + operator.
L1 = ['a', 'b'] L2 = [1, 2] L3 = ['Learn', 'Python'] print( L1 + L2 + L3 ) # ['a', 'b', 1, 2, 'Learn', 'Python']
b) Alternatively, you can join lists using the extend() method.
L1 = ['a', 'b'] L2 = ['c', 'd'] L1.extend(L2) print(L1) # ['a', 'b', 'c', 'd']
c) Next, you can append a value to a list by calling the append() method. See the below example.
L1 = ['x', 'y'] L1.append(['a', 'b']) print(L1) # ['x', 'y', ['a', 'b']]
Slicing Operation on Python List
Slicing [::] is a magical operator which you can use to extract the part of a list based on specific indices. Apart from the list, it works with different Python data types such as strings, tuples, etc. Refer to the following slicing syntax to learn how to use it effectively.
#The Python slicing operator syntax sublist = my_list[start_index:end_index:step]
my_list
refers to the list you want to slice.start_index
specifies the index at which the slice should start (inclusive).end_index
specifies the index at which the slice should end (exclusive).step
is an optional parameter that determines the step size or the number of elements to skip (defaults to 1 if not specified)
Here are some simple examples demonstrating how the slicing operator can be used with lists:
a) Extracting a Range of Elements:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sublist = my_list[2:6]
The sublist will contain elements from index 2 to index 5 (exclusive), which are [3, 4, 5, 6].
b) Extracting Every Other Element:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sublist = my_list[::2]
c) The sublist will contain every other element from the original list, resulting in [1, 3, 5, 7, 9].
Reversing a List:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] reversed_list = my_list[::-1]
The reversed_list will contain the elements of the original list in reverse order, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].
Iterate Over a Python List
a) The for loop in Python is the most trivial way to iterate over a list., Please ensure that you follow proper Python indentation rules. while using a for loop.
theList = [1, 3, 5, 7] for element in theList: print(element)
If you want both the element and the index, call the enumerate() function. See the below example.
theList = [1, 3, 5, 7] for index, element in enumerate(theList): print(index, element)
If you only want the index, then call the range() and len() methods.
theList = [1, 3, 5, 7] for index in range(len(theList)): print(index)
b) The list elements support the iterator protocol. To intentionally create an iterator, call the built-in iter function.
it = iter(theList) element = it.next() # fetch first value element = it.next() # fetch second value
Check out the below example.
theList = ['Python', 'C', 'C++', 'Java', 'CSharp'] for language in theList: print("I like", language) # run it to check the result
Search Elements in a List
a) You can use the Python ‘in’ operator to check if an item is present in the list.
# Syntax if value in theList: print("list contains", value)
Here’s an example:
fruits = ['apple', 'banana', 'orange', 'grape'] # Check if 'banana' is present in the list of fruits if 'banana' in fruits: print("Banana is in the list of fruits!") # Check if 'watermelon' is present in the list of fruits if 'watermelon' in fruits: print("Watermelon is in the list of fruits!") else: print("Watermelon is not in the list of fruits!") """ Output Banana is in the list of fruits! Watermelon is not in the list of fruits! """
b) Using the list index() method, you can find out the position of the first matching item.
# Syntax to use loc = theList.index(value)
The index method performs a linear search and breaks after locating the first matching item. If the search ends without a result, then it throws a ValueError exception.
values = 1, 2 theList = [2,3,4] for value in values: try: loc = theList.index(value) print(f"The value {value} matched") # match except ValueError: loc = -1 print(f"The value {value} not matched") # no match
Sort Lists
a) The list class implements a sort() method for ordering (in both ascending and descending order) its elements in place.
# Check how to use list's sort method theList.sort()
By default, the function sort() performs sorting in the ascending sequence.
theList = ['a','e','i','o','u'] theList.sort() print(theList) # ['a', 'e', 'i', 'o', 'u']
If you wish to sort in descending order, then refer to the below example.
theList = ['a','e','i','o','u'] theList.sort(reverse=True) print(theList) # ['u', 'o', 'i', 'e', 'a']
b) You can use the built-in sorted() function to return a copy of the list with its elements ordered.
# How to use sorted() function newList = sorted(theList)
By default, it also sorts in an ascending manner.
theList = ['a','e','i','o','u'] newList = sorted(theList) print("Original list:", theList, "Memory addr:", id(theList)) print("Copy of the list:", newList, "Memory addr:", id(newList))
Check the results below:
Original list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 55543176 Copy of the list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 11259528
You can turn on the “reverse” flag to “True” for enabling the descending order.
theList = ['a','e','i','o','u'] newList = sorted(theList, reverse=True) print("Original list:", theList, "Memory addr:", id(theList)) print("Copy of the list:", newList, "Memory addr:", id(newList))
The results are as follows:
Original list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 56195784 Copy of the list: ['u', 'o', 'i', 'e', 'a'] Memory addr: 7327368
List Class Methods
1- Python List’s append() – It adds a new element to the end of the list.
2- Python List’s extend() – It extends a list by adding elements from another list.
3- Python List’s insert() – It injects a new element at the desired index.
4- Python List’s remove() – It deletes the desired element from the list.
5- Python List’s pop() – It removes as well as returns an item from the given position.
6- Python List’s clear() – It flushes out all elements of a list.
7- Python List’s index() – It returns the index of an element that matches first.
8- Python List’s count() – It returns the total no. of elements passed as an argument.
9- Python List’s sort() – It orders the elements of a list in an ascending manner.
10- Python List’s reverse() – It inverts the order of the elements in a list.
11- Python List’s copy() – It performs a shallow copy of the list and returns.
List’s Built-in Functions
1- Python all() – It returns True if the list has elements with a True value or is blank.
2- Python any() – If any of the members has a True value, then it also returns True.
3- Python enumerate() – It returns a tuple with an index and value of all the list elements.
4- Python len() – The return value is the size of the list.
5- Python list() – It converts all iterable objects and returns them as a list.
6- Python max() – The member having the maximum value
7- Python min() – The member having the minimum value
8- Python sorted() – It returns the sorted copy of the list.
9- Python sum() – The return value is the aggregate of all elements of a list.
Wrapping Up
In this tutorial, we tried to cover one of the essential topics, i.e., Lists in Python. In whatever domain of Python, you choose to work, knowing lists is essentially help.
Anyways, if you find something new to learn today, then do share it with others. And, follow us on our social media accounts to see more of this.
Best,
TechBeamers