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.

Video: Python Lists and Tuples

In Python, lists are used to store multiple data at once. For example,

Suppose we need to record the ages of 5 students. Instead of creating 5 separate variables, we can simply create a list:

List Elements
Lists Elements

Create a Python List

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

# A list with 3 integers
numbers = [1, 2, 5]

print(numbers)

# Output: [1, 2, 5]

Here, we have created a list named numbers with 3 integer items.

A list can have any number of items and they may be of different types (integer, float, string, etc.). For example,

# empty list
my_list = []

# list with mixed data types
my_list = [1, "Hello", 3.4]

Access Python List Elements

In Python, each item in a list is associated with a number. The number is known as a list index.

We can access elements of an array using the index number (0, 1, 2 …). For example,

languages = ["Python", "Swift", "C++"]

# access item at index 0
print(languages[0])   # Python

# access item at index 2
print(languages[2])   # C++

In the above example, we have created a list named languages.

List Index in Python
List Indexing in Python

Here, we can see each list item is associated with the index number. And, we have used the index number to access the items.

Note: The list index always starts with 0. Hence, the first element of a list is present at index 0, not 1.


Negative Indexing in Python

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

Let's see an example,

languages = ["Python", "Swift", "C++"]

# access item at index 0
print(languages[-1])   # C++

# access item at index 2
print(languages[-3])   # Python
Python List Negative Indexing
Python Negative Indexing

Note: If the specified index does not exist in the list, Python throws the IndexError exception.


Slicing of a Python List

In Python it is possible to access a section of items from the list using the slicing operator :, not just a single item. For example,

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# items from index 2 to index 4
print(my_list[2:5])

# items from index 5 to end
print(my_list[5:])

# items beginning to end
print(my_list[:])

Output

['o', 'g', 'r']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

Here,

  • my_list[2:5] returns a list with items from index 2 to index 4.
  • my_list[5:] returns a list with items from index 1 to the end.
  • my_list[:] returns all list items

Note: When we slice lists, the start index is inclusive but the end index is exclusive.


Add Elements to a Python List

Python List provides different methods to add items to a list.

1. Using append()

The append() method adds an item at the end of the list. For example,

numbers = [21, 34, 54, 12]

print("Before Append:", numbers)

# using append method
numbers.append(32)

print("After Append:", numbers)

Output

Before Append: [21, 34, 54, 12]
After Append: [21, 34, 54, 12, 32]

In the above example, we have created a list named numbers. Notice the line,

numbers.append(32)

Here, append() adds 32 at the end of the array.

2. Using extend()

We use the extend() method to add all items of one list to another. For example,

prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)

even_numbers = [4, 6, 8]
print("List2:", even_numbers)

# join two lists
prime_numbers.extend(even_numbers)

print("List after append:", prime_numbers) 

Output

List1: [2, 3, 5]
List2: [4, 6, 8]
List after append: [2, 3, 5, 4, 6, 8]

In the above example, we have two lists named prime_numbers and even_numbers. Notice the statement,

prime_numbers.extend(even_numbers)

Here, we are adding all elements of even_numbers to prime_numbers.


Change List Items

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

languages = ['Python', 'Swift', 'C++']

# changing the third item to 'C'
languages[2] = 'C'

print(languages)  # ['Python', 'Swift', 'C']

Here, initially the value at index 3 is 'C++'. We then changed the value to 'C' using

languages[2] = 'C'

Remove an Item From a List

1. Using del()

In Python we can use the del statement to remove one or more items from a list. For example,

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item
del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item
del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']

# delete first two items
del languages[0 : 2]  # ['C', 'Java', 'Rust']
print(languages)

2. Using remove()

We can also use the remove() method to delete a list item. For example,

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# remove 'Python' from the list
languages.remove('Python')

print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

Here, languages.remove('Python') removes 'Python' from the languages list.


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

We can use the for loop to iterate over the elements of a list. For example,

languages = ['Python', 'Swift', 'C++']

# iterating through the list
for language in languages:
    print(language)

Output

Python
Swift
C++

Check if an Item Exists in the Python List

We use the in keyword to check if an item exists in the list or not. For example,

languages = ['Python', 'Swift', 'C++']

print('C' in languages)    # False
print('Python' in languages)    # True

Here,

  • 'C' is not present in languages, 'C' in languages evaluates to False.
  • 'Python' is present in languages, 'Python' in languages evaluates to True.

Python List Length

In Python, we use the len() function to find the number of elements present in a list. For example,

languages = ['Python', 'Swift', 'C++']

print("List: ", languages)

print("Total Elements: ", len(languages))    # 3

Output

List:  ['Python', 'Swift', 'C++']
Total Elements:  3

Python List Comprehension

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

A list comprehension consists of an expression followed by the for statement inside square brackets.

Here is an example to make a list with each item being increasing by power of 2.

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

print(numbers)    

# Output: [1, 4, 9, 16, 25]

In the above example, we have used the list comprehension to make a list with each item being increased by power of 2. Notice the code,

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

The code above means to create a list of number*number where number takes values from 1 to 5

The code above,

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

is equivalent to

numbers = []

for x in range(1, 6):
    numbers.append(x * x)
Did you find this article helpful?