Python Lists

In python, List is a collection of an ordered sequence of items, and you can store the values of different data types.

 

In python, you can create the list by enclosing the list items within brackets [ ] and the list items must be separated by commas.

 

Following is the example of creating a list with a different type of items in python.

 

# List with integer types
a = [30, 10, 20]
# List with string types
b = ["Suresh", "Rohini", "Trishi", "Hanshith"]
# List with mix types
c = [10, "Tutlane", 20]
# Empty List
d = [] print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)

If you observe the above example, we created different lists and printing the list items using print method in python.

 

When you execute the above python program, you will get the result as shown below.

 

a =  [30, 10, 20]
b =  ['Suresh', 'Rohini', 'Trishi', 'Hanshith']
c =  [10, 'Tutlane', 20]
d =  []

Access Elements from List

In python, you can access elements from the list by using index values. In list, the index values will always start from 0. If your list has 4 elements, you can access elements from the list using index ranges 0 to 3.

 

Following is the example of accessing the elements from the list in python.

 

lst = [10, 20, 30, "Tutlane"]
print(lst[0])
print(lst[2])
print(lst[3])

If you observe the above example, we are accessing elements from list using different index values with square brackets [ ].

 

When you execute the above python example, you will get the result as shown below.

 

10
30
Tutlane

In python, you can also use negative indexing to access list elements starting from the end. The index value -1 will refer to the last item, -2 refers to the second-last item, and so on.

 

Following is the example of accessing elements from a list using negative indexing in python.

 

lst = [10, 20, 30, "Tutlane"]
print(lst[-1])
print(lst[-2])
print(lst[-4])

When you execute the above python list example, you will get the result like as shown below.

 

Tutlane
30
10

If you try to access elements from a list that does not exist at the specified index, you will get an index error like “list index out of range”.

 

lst = [10, 20, 30, "Tutlane"]
print(lst[5])
print(lst[6])

If you observe the above example, the list has only 4 elements that mean you can access the list elements using the 0 to 3 index range. Still, we are trying to access the list elements that don’t exist in the specified index range.

 

When you try to execute the above python list example, you will get an index out of range exception like as shown below.

 

Traceback (most recent call last):
  File "pythonlist.py", line 2, in <module>
    print(lst[5])
IndexError: list index out of range

Access Range of Values from List

In python, if you want to access a range of items from the list, you can use index ranging by specifying the starting and ending positions with the colon ( : ) operator. The index range will return a new list with the specified range of items.

 

Following is the example of accessing the specified range of elements from the list using a range of indexes in python.

 

lst = [10, 20, 30, "tutlane", "learn", "python"]
print(lst[1:4])

When you execute the above python list example, you will get the result like as shown below.

 

[20, 30, 'tutlane']

When you are slicing the list by defining the index range values, the search will start from the specified starting index position and end one item before the ending index position because the index positions will start from 0.

 

If you observe the above result, the list items slicing started from the index position 1 and stopped one item before the end index position 4.

 

It’s optional to define the starting and ending index positions in python to get the range of values from the list. If you skip mentioning the starting index position, the range will start from the first item the same way if you skip mentioning the ending index position, the range will continue to the end of the list.

 

Following is the example of getting the range of list items with or without specifying the starting and ending index list items.

 

lst = [10, 20, 30, "tutlane", "learn", "python"]
# Without index values
print(lst[:])
# Only starting index
print(lst[2:])
# Only ending index
print(lst[:5])

When you execute the above python list example, you will get the result like as shown below.

 

[10, 20, 30, 'tutlane', 'learn', 'python']
[30, 'tutlane', 'learn', 'python']
[10, 20, 30, 'tutlane', 'learn']

You can also use negative indexing values in python to get the range of values from the list. Following is the example of getting the range of list elements using negative index values.

 

lst = [10, 20, 30, "tutlane", "learn", "python"]
print(lst[-3:-1])
print(lst[-4:-2])
print(lst[-2:])

When you execute the above python list example, you will get a result like as shown below.

 

['tutlane', 'learn']
[30, 'tutlane']
['learn', 'python']

Change List Item Value

Using index values, you can change or update the value of the required item in the list.

 

Following is the example of changing the particular list item value using index number in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ",lst)
lst[1] = 5
lst[3] = 40
lst[4] = 50
print("After: ",lst)

When you execute the above python list example, you will get the result like as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 5, 30, 40, 50]

Add or Append Items to List

In python, the list append() method is useful to add or append items at the end of the list.

 

Following is the example of adding items to the list using append() method in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
lst.append(40)
lst.append("python")
print(lst)

The above python list example will return the result as shown below.

 

[10, 20, 30, 'tutlane', 'learn', 40, 'python']

Insert Items in List

If you want to insert items in the list at a specified index position, use the list insert() method.

 

Following is the example of inserting the items in the list at specified index positions using insert() method in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
lst.insert(1, 40)
lst.insert(4, "python")
print("After: ", lst)

The above python list example will return the result as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 40, 20, 30, 'python', 'tutlane', 'learn']

Remove Elements from List

In python, you can delete/remove items from a list using either del keyword, remove(), pop(), or clear() methods based on our requirements.

 

The del keyword is useful to remove list items at specified index positions or delete the list completely.

 

Following is the example of using the del keyword to delete the list items at specified index positions in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
del lst[1]
del lst[3]
print("After: ", lst)

The above python list example will return the result as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 30, 'tutlane']

If required, you can also delete the complete list using the del keyword in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
del lst print(lst)

If you observe the above example, we are deleting the complete list using the del keyword and trying to print the list. The above example will return the result as shown below.

 

Traceback (most recent call last):
  File "pythonlist.py", line 3, in <module>
    print(lst)
NameError: name 'lst' is not defined

We got an exception because we tried to print the list (lst) that is already deleted.

 

In python, if you want to remove list items based on the value, you can use the list remove() method.

 

Following is the example of removing the list items based on the value using the list remove() method.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
lst.remove(20)
lst.remove("learn")
print("After: ", lst)

The above python list example will return the result as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 30, 'tutlane']

In python, the list pop() method is useful to remove the list items based on the specified index position. If the index position is not specified, by default, it will remove the last item.

 

Following is the example of using the list pop() method to remove list items.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
lst.pop(2)
lst.pop()
print("After: ", lst)

When you execute the above python list program, you will get the result like as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 20, 'tutlane']

If you want to clear or empty a list items, you can use the list clear() method.

 

Following is the example of removing all list elements using the clear() method in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
lst.clear()
print("After: ", lst)

The above python list example will return the result as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: []

List Length

In python, to count the number of items in the list, use the len() function.

 

Following is the example of using len() function in python to get the list length/size.

 

lst = [10, 10, 20, 20, 30, "tutlane", "learn"]
print("List Size: ", len(lst)) #List Size: 7

By using len() function, you can also check whether the list is empty or not like as shown below.

 

lst = []
count = len(lst)
if count > 0:
    print("List size: ", count)
else:
    print("List is empty")

The above list example will return the result like as shown below.

 

List is empty

Join or Concatenate lists

In python, the + operator is useful for joining or concatenating multiple lists and returning a new list with all the elements.

 

Following is the example of joining the lists using + operator in python.

 

lst1 = [10, 20, "tutlane"]
lst2 = [10, "learn", "python"]
lst3 = lst1 + lst2
print(lst3)

The above list example will return the result like as shown below.

 

[10, 20, 'tutlane', 10, 'learn', 'python']

Check If Item Exists in List

By using in and not in operators, you can check whether the particular item exists in the list or not.

 

Following is the example to verify whether the particular exists in the list or not using in operator in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("20 in list: ", 20 in lst)
print("tutlane in list: ", "tutlane" in lst)
print("50 in list: ", 50 in lst)

The above list example will return the result like as shown below.

 

20 in list: True
tutlane in list: True
50 in list: False

Loop through a List

By using for loop, you can loop through the items of the list based on your requirements.

 

Following is the example of looping through the list items using for loop in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
for item in lst:
    print(item)

The above list example will return the result like as shown below.

 

10
20
30
tutlane
learn

Python Copy List

In python, you can copy a list using the list copy() method or list() method, but directly copying the list like list2 = list1 is not allowed because the list2 will reference list1. So, the changes you made in list1 will automatically reflect in the list2.

 

Following is the example of using the list copy() method to copy a list in python.

 

lst1 = [10, 20, 30, "tutlane", "learn"]
lst2 = []
print("====Before Copy====")
print("List1: ", lst1)
print("List2: ", lst2)
lst2 = lst1.copy()
print("====After Copy====")
print("List1: ", lst1)
print("List2: ", lst2)

The above list example will return the result like as shown below.

 

====Before Copy====
List1: [10, 20, 30, 'tutlane', 'learn']
List2: []
====After Copy====
List1: [10, 20, 30, 'tutlane', 'learn']
List2: [10, 20, 30, 'tutlane', 'learn']

Following is the example of using a built-in list() method to copy a list in python.

 

lst1 = [10, 20, 30, "tutlane", "learn"]
lst2 = []
print("====Before Copy====")
print("List1: ", lst1)
print("List2: ", lst2)
lst2 = list(lst1)
print("====After Copy====")
print("List1: ", lst1)
print("List2: ", lst2)

The above list example will return the result like as shown below.

 

====Before Copy====
List1: [10, 20, 30, 'tutlane', 'learn']
List2: []
====After Copy====
List1: [10, 20, 30, 'tutlane', 'learn']
List2: [10, 20, 30, 'tutlane', 'learn']

Python Reverse List

Using the list reverse() method, you can reverse the sorting order of the list elements.

 

Following is the example of reversing the list items using the reverse() method in python.

 

lst = [10, 20, 30, "tutlane", "learn"]
print("Before: ", lst)
lst.reverse()
print("After: ",lst)

The above list example will return the result like as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: ['learn', 'tutlane', 30, 20, 10]

Python Sort List Elements

In python, the list sort() method is useful to sort the list elements. By default, the sort() method will sort the list elements in ascending order.

 

Following is the example of sorting the list elements in ascending order using the sort() method in python.

 

lst = ["tutlane", "learn", "python"]
print("Before: ", lst)
lst.sort()
print("After: ",lst)

The above list example will return the result like as shown below.

 

Before: ['tutlane', 'learn', 'python']
After: ['learn', 'python', 'tutlane']

To sort the list elements in descending order, you need to use optional reverse = True property with sort() method like as shown below. 

 

lst = ["learn", "python", "tutlane"]
print("Before: ", lst)
lst.sort(reverse = True)
print("After: ",lst)

The above list example will return the result like as shown below.

 

Before: ['learn', 'python', 'tutlane']
After: ['tutlane', 'python', 'learn']

To sort list items either in ascending or descending order, you need to make sure that all the list items must be the same type. Otherwise, you will get an TypeError exception.

 

lst = [30, 20, 10, "tutlane", "learn"]
print("Before: ", lst)
lst.sort()
print("After: ",lst)

When you execute the above python list example, you will get the result like as shown below.

 

Traceback (most recent call last):
  File "pythonlists.py", line 3, in <module>
    lst.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

Remove Duplicates from List

To remove duplicates from the python list, you need to use the dictionary object fromkeys() method because we don’t have any direct method to remove duplicates from the list.

 

Following is the example of removing duplicates from a list in python.

 

lst = [10, 10, 20, 20, 30, "tutlane", "tutlane"]
print("Before: ", lst)
lst = list(dict.fromkeys(lst))
print("After: ", lst)

Generally, the dictionary object will not allow duplicate keys. In the above example, we created a dictionary object by considering the list (lst) items as keys. So, the dictionary object will automatically remove the duplicate keys. Again we converted the dictionary object to a list.

 

The above python list example will return the result as shown below.

 

Before: [10, 10, 20, 20, 30, 'tutlane', 'tutlane']
After: [10, 20, 30, 'tutlane']

Python List Methods

In python, the list object has a set of built-in methods to perform different operations like adding items to a list, remove elements from the list, etc., based on your requirements.

 

Following are the built-in list methods available in the python programming language.

 

MethodDescription
append() It is useful to add elements at the end of the list.
insert() It is useful to add elements at the specified position.
extend() It is useful to add elements of one list to the end of another list.
pop() It is useful to remove the element at the specified position.
remove() It is useful to remove the element with the specified value.
clear() It is useful to remove all the elements of a list.
index() It will return the index of the first matched element.
count() It will return the number of elements with the specified value.
sort() It is useful to sort (ascending/descending) list items.
reverse() It is useful to reverse the order of list items.
copy() It is useful to return a copy of the list.