The list is a most versatile datatype available in Python which can be written as a list of comma-separated values between square brackets[]. Python List allows duplicate values. An index number is used to access a particular list element.
How to create a list
Note: if you use ( ) then it will be tuple instead on list.
li_1 = [] # Empty list li_1 = [1,2,3] # List of integers li_2 = ['car','truck','bus',5] # List of mixed datatypes
List Indexing
Python also supports negative indexing means -1 refer to the last elements of the list, -2 refers to the second last elements of the list.
. . .
Assignment operator ‘=’ with a list does not make the copy. Instead, the assignment makes the two variables point to the one list in memory.
>>> vehicle = ['car','bus','truck'] >>> vehicle_copy = vehicle # Does not copy the vehicle list >>> vehicle_copy ['car','bus','truck'] >>> vehicle_copy.remove('bus') >>> vehicle_copy ['car','truck'] >>> vehicle ['car','truck']
If we create the list from another list using an assignment operator, both list will point the same memory address. So, if any changes are made with one list, it will have to reflect with another list also.
List Copy
Use Python’s copy() method to copy the list.
>>> color = ['green','red','yellow'] >>> color_copy = color.copy() #correct way to copy list >>> color_copy ['green', 'red', 'yellow'] >>> color_copy.remove('green') >>> color_copy ['red', 'yellow'] >>> color ['green', 'red', 'yellow']
Access List Items
Used index number to access the list elements.
Note: End index is exclusive.
>>> li = ['car','truck','bus',5] >>> li[0] 'car' >>> li[2] 'bus' >>> li[-3] 'truck'
List Slices
Slices work on list same as string. You can also access the range of list elements by defining the first and last index in [start : end] brackets separated by a colon.
>>> li = ['car','truck','bus',5] >>> li[0:2] ['car', 'truck'] # The default value of start is 0. If you don't define the start value, it will start from begin. >>> li[:3] ['car', 'truck', 'bus'] >>> li[-3:-1] ['truck', 'bus'] >>> li[1:] ['truck', 'bus', 5]
Change Element: Used index number to change the value of a specific element.
>>> li = ['car','truck','bus',5] >>> li[1] = 'bicycle' >>> li ['car', 'bicycle', 'bus', 5]
Add Element:
- list.append(elem) function is used to add a single element at the end of the list. It doesn’t return the new list, just modifies the original list.
- list.insert(index, elem) function is used to add an element at the specified index and shifting elements to the right. It doesn’t return the new list, just modifies the original list.
- list.extend(list2) function add the elements of the list2 to the end of the list. This function also made the changes in place, does not return.
>>> li = ['car', 'bicycle', 'bus', 5] >>> li.append('scooter') >>> li ['car', 'bicycle', 'bus', 5, 'scooter'] >>> li.insert(2,'train') >>> li ['car', 'bicycle', 'train', 'bus', 5, 'scooter'] >>> li2 = ['dog','cat', 1.25] >>> li.extend(li2) >>> li ['car', 'bicycle', 'train', 'bus', 5, 'scooter', 'dog', 'cat', 1.25]
Remove Element:
- list.remove(elem) function used to remove the first instance of a specified element from the list. It throws ValueError if the element is not present.
- list.pop(index) function is used to remove and return the last element if the index is not specified or remove the specified Index element.
- del Keyword remove specified index element. It also removes the complete list.
- clear() function used to empty the list.
>>> li = ['car', 'bicycle', 'train', 'bus', 5, 'scooter'] >>> li.remove('bus') >>> li ['car', 'bicycle', 'train', 5, 'scooter'] >>> li.pop() 'scooter' >>> li ['car', 'bicycle', 'train', 5] >>> del li[-1] >>> li ['car', 'bicycle', 'train'] >>> del li # This line remove the entire list li >>> li.clear() >>> li [] # empty list
Loop through a List: You can loop through the list items by using a for loop.
>>> fruit_li = ["banana","apple","Orange"] >>> for e in fruit_li: ... print(e) # This line print all elements of the list Output: banana apple Orange
Check if Item Exists: Used in and not in membership operator to check specified element exist in list or not.
>>> fruit_li = ["banana","apple","Orange"] >>> if "Orange" in fruit_li: ... print("Element exist") Output: Element exist
. . .
Python provides the various built-in functions for a list operation. This tutorial has explained it with examples.
list.index(elem) – method returns the index of the given element. It throws a ValueError if the element does not exist in the list.
>>> fruit_li = ["banana","apple","Orange"] >>> fruit_li.index('apple') 1 >>> fruit_li.index('strawberry') ValueError: 'strawberry' is not in list
>>> li = [1,2,3,4,5,6,7] # Gives the total number of elements in a list >>> len(li) 7 >>> max(li) # Return the element from a list with a max value 7 >>> min(li) # Return the element from a list with a min value 1 >>> li.reverse() # Reverse the list in place. (does not return it) >>> li [7, 6, 5, 4, 3, 2, 1] >>> li.sort() # Sort the list in place. (does not return it) >>> li [1, 2, 3, 4, 5, 6, 7] >>> li_1 = [1,2,3,4,5] >>> li_2 = [10,20,30] >>> li_1 + li_2 # Join two list [1,2,3,4,5,10,20,30]
. . .