Python List

In this tutorial, we will learn about Python lists (creating lists, changing list items, removing items and other list operations) with the help of examples.

In Python, lists are used to store multiple items at once. They are similar to arrays in other programming languages. For example,

cars = ['BMW', 'Tesla', 'Ford']

Creating Lists

A list is created by placing items inside [], separated by commas . For example,

# A list with 3 items
numbers = [1, 2, -5]
# List containing duplicate values
numbers = [1, 2, -5, 2]
# empty list
numbers = []

In Python, a list may contain items of different types. For example,

# A list with 3 items of different types
random_list = [5, 2.5, 'Hello']

A list may also contain another list as an element. For example,

# A list with two items: 5 and [4, 5, 6]
random_list = [5, [4, 5, 6]]

Access List Elements

The items of a list are in order, and we can access individual items of a list using indexes. For example,

cars = ['BMW', 'Tesla', 'Ford']
# access the first item
print(cars[0])    # BMW
# access the third item
print(cars[2])    # Ford

In Python, indexing starts from 0. Meaning,

  • the index of the first item is 0
  • the index of the second item is 1
  • and so on
Python list indexing starts from 0
Python List

Hence, cars[0] gives the first item of the cars list, cars[1] gives the second item, and so on.

Negative Indexing

Python lists also support negative indexing.

  • the index of the last item is -1
  • the index of the second last item is -2
  • and so on
Python list negative index
Python Negative Indexing
cars = ['BMW', 'Tesla', 'Ford']
# access the last item
print(cars[-1])    # Ford
# access the third last item
print(cars[-3])    # BMW

By the way, if the specified index does not exist in the list, Python throws the IndexError exception.

cars = ['BMW', 'Tesla', 'Ford']
# trying to access the fourth item
# however, the list only has three items
print(cars[3])

Output

Traceback (most recent call last):
    File "<string>", line 4, in <module>
IndexError: list index out of range

Slicing of a List

It is also possible to access a section of items from the list, not just a single item (using the slicing notation). For example,

languages = ['Python', 'JavaScript', 'C++', 'Kotlin']
# first three items -> 0, 1, 2
print(languages[0: 3])    # ['Python', 'JavaScript', 'C++']
# second to last items -> 1, 2, 3
print(languages[1: 4])    # ['JavaScript', 'C++', 'Kotlin']

One thing to remember about list slicing is that the start index is inclusive, whereas the end index is exclusive.

Hence,

  • languages[0: 3] returns a list with items at index 0, 1, and 2 but not 3.
  • languages[1: 4] returns a list with items at index 1, 2, and 3 but not 4.

Slicing: Skip Start and End Index

If we use the empty start index, the slicing starts from the beginning of the list. Similarly, if we use the empty end index, the slicing ends at the last index.

languages = ['Python', 'JavaScript', 'C++', 'Kotlin']
# elements from index 0 to 1
print(languages[:2])    # ['Python', 'JavaScript']  
# elements from index 2 to last index
print(languages[2:])    # ['C++', 'Kotlin']

Change List Items

Python lists are mutable. Meaning lists are changeable. And, we can change items of a list by assigning new values. For example,

cars = ['BMW', 'Tesla', 'Ford']
# changing the second item to 'Toyota'
cars[1] = 'Toyota'
print(cars)    # ['BMW', 'Toyota', 'Ford']

Remember, list indexing starts from 0, not 1. Hence, to change the second item, we have to assign a new value to cars[1] and not cars[2].


Delete List

We can remove one or more items from a list using Python's del statement. The del statement can also be used to delete the list itself as well.

cars = ['BMW', 'Tesla', 'Ford', 'Toyota']
# deleting the second item
del cars[1]
print(cars)    # ['BMW', 'Ford', 'Toyota']
# deleting the last item
del cars[-1]
print(cars)    # ['BMW', 'Ford']
# deleting the list
del cars
print(cars)    # Error: name 'cars' is not defined

Python List Length

We can find the length of a list using the len() built-in function. For example,

cars = ['BMW', 'Tesla', 'Ford', 'Toyota']
print(len(cars))    # 4
del cars[0]
print(len(cars))    # 3

Python List Methods

Python has many useful list methods that makes it really easy to work with lists.

Method Description
append() add an item to the end of the list
extend() add items of lists and other iterables to the end of the list
insert() inserts an item at the specified index
remove() removes item present at the given index
pop() returns and removes item present at the given index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the specified item in the list
sort() sort the list in ascending/descending order
reverse() reverses the item of the list
copy() returns the shallow copy of the list

Iterating through a List

It's really easy to iterate through a list using a for loop.

cars = ['BMW', 'Tesla', 'Ford', 'Toyota']

# iterating through the list
for car in cars:
    print(car)

Output

BMW
Tesla
Ford
Toyota

Check if an Item Exists in the List

We can use the in keyword to check if an item exists in the list or not.

cars = ['BMW', 'Tesla', 'Ford', 'Toyota']
print('Kia' in cars)    # False
print('Kia' not in cars)    # True
print('BMW' in cars)    # True

Python List Comprehension

List comprehension is a concise and elegant way to create lists. For example,

# this code means
# create a list of x*x where
# x takes values from 1 to 5 (range(1, 6))
numbers = [x*x for x in range(1, 6)]

print(numbers)    # [1, 4, 9, 16, 25]

Here, this code

numbers = [x*x for x in range(1, 6)]

is equivalent to

numbers = []

for x in range(1, 6):
    numbers.append(x * x)

Visit Python List Comprehension.


Python List Summary

In Python, a list is

  • collection - can contain multiple items
  • ordered - items of a list are in order
  • changeable - items of a list can be changed

Recommended Reading: Python Tuple

Did you find this article helpful?