Python List

What is Python List?

A list is a sequence of values (similar to an array in other programming languages but more versatile)

The values in a list are called items or sometimes elements.

The important properties of Python lists are as follows:

  • Lists are ordered – Lists remember the order of items inserted.
  • Accessed by index – Items in a list can be accessed using an index.
  • Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.
  • Lists are changeable (mutable) – You can change a list in-place, add new items, and delete or update existing items.

Create a List

You can create a list by placing a comma-separated sequence of values in square brackets [].

Examples:

# A list of integers
L = [1, 2, 3]
# A list of strings
L = ['red', 'green', 'blue']

The items of a list don’t have to be the same type. The following list contains an integer, a string, a float, a complex number, and a boolean.

Example:

# A list of mixed datatypes
L = [ 1, 'abc', 1.23, (3+4j), True]

A list containing zero items is called an empty list and you can create one with empty
brackets []

Example:

# An empty list
L = []

There is one more way to create a list based on existing list, called List comprehension.

The list() Constructor

You can convert other data types to lists using Python’s list() constructor.

Example: Convert a string to a list of one-character strings

L = list('abc')
print(L)    # ['a', 'b', 'c']

Example: Convert a tuple to a list

L = list((1, 2, 3))
print(L)    # [1, 2, 3]

Nested List

A list can contain sublists, which in turn can contain sublists themselves, and so on. This is known as nested list.

You can use them to arrange data into hierarchical structures.

Example: Create a nested list

# Nested list
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Read more about it in the nested list tutorial.

Access List Items by Index

You can access individual items in a list using an index in square brackets.

Note that list indexing always starts from 0.

The indexes for the items in a list are illustrated as below:

Python List Indexing

Example: Access 1st and 3rd list items

L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[0])		# red
print(L[2])		# blue

Python will raise an IndexError error, if you use an index that exceeds the number of items in your list.

Example:

# IndexError: list index out of range
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[5])

Negative List Indexing

You can access a list by negative indexing as well.

Negative indexes count backward from the end of the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.

The negative indexes for the items in a list are illustrated as below:

Python Negative List Indexing

Example: Access last and 2nd last list items

L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[-1])    # black
print(L[-2])    # yellow

Access Nested List Items

Similarly, you can access individual items in a nested list using multiple indexes.

The first index determines which list to use, and the second indicates the value within that list.

The indexes for the items in a nested list are illustrated as below:

Python Nested List Indexing

Example: Access items of a nested list

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[2][2])     # ['eee', 'fff']
print(L[2][2][0])  # eee

Slicing a List

You can extract a sub-sequence of a list by using a slice. A slice of a list is also a list.

Example:

L = ['a', 'b', 'c', 'd', 'e', 'f']

print(L[2:5])		# ['c', 'd', 'e']
print(L[0:2])		# ['a', 'b']
print(L[3:-1])		# ['d', 'e']

Read more about it in the list slicing tutorial.

Change Item Value

To change the value of a specific item in a list, refer to its index number.

Example: Change the value of the first and last item in a list

L = ['red', 'green', 'blue']

L[0] = 'orange'
print(L)    # ['orange', 'green', 'blue']

L[-1] = 'violet'
print(L)    # ['orange', 'green', 'violet']

Add items to a list

To add new values to a list, use append() method.

Example: Append ‘blue’ to the end of the list

L = ['red', 'green', 'yellow']
L.append('blue')
print(L)    # ['red', 'green', 'yellow', 'blue']

The append() method adds items only to the end of the list.

When you want to insert an item at a specific position in a list, use insert() method.

Example: Insert ‘blue’ at 2nd position

L = ['red', 'green', 'yellow']
L.insert(1,'blue')
print(L)    # ['red', 'blue', 'green', 'yellow']

Note that all of the values in the list after the inserted value will be moved down one index.

Combine Lists

You can merge one list into another by using extend() method.

Example: Merge one list into another

L = ['red', 'green', 'yellow']
L.extend([1,2,3])
print(L)    # ['red', 'green', 'yellow', 1, 2, 3]

Alternatively, you can use the concatenation operator + or the augmented assignment operator +=

Example: Append items to a list

# concatenation operator
L = ['red', 'green', 'blue']
L = L + [1,2,3]
print(L)    # ['red', 'green', 'blue', 1, 2, 3]
# augmented assignment operator
L = ['red', 'green', 'blue']
L += [1,2,3]
print(L)    # ['red', 'green', 'blue', 1, 2, 3]

List Replication

You can replicate items in a list using the replication operator *

Example: Replicate list items three times

L = ['red']
L = L * 3
print(L)    # ['red', 'red', 'red']

Remove items from a list

There are several ways to remove items from a list.

Remove an Item by Index

If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.

If no index is specified, pop() removes and returns the last item in the list.

Example: Remove and return 2nd item from the list

L = ['red', 'green', 'blue']
x = L.pop(1)
print(L)	# ['red', 'blue']

# removed item
print(x)	# green

If you don’t need the removed value, use the del statement.

Example: Remove 2nd item from the list

L = ['red', 'green', 'blue']
del L[1]
print(L)	# ['red', 'blue']

Remove an Item by Value

If you’re not sure where the item is in the list, use remove() method to delete it by value.

Note that the method searches for the first instance of the given item and removes it.

Example: Remove ‘red’ from the list

L = ['red', 'green', 'blue', 'red']
L.remove('red')
print(L)	# ['green', 'blue', 'red']

Remove Multiple Items

To remove more than one items, use the del keyword with a slice index.

Example: Remove three items from the list

L = ['red', 'green', 'blue', 'yellow', 'black']
del L[1:4]
print(L)	# ['red', 'black']

Remove all Items

Use clear() method to remove all items from the list.

Example: Make whole list empty

L = ['red', 'green', 'blue']
L.clear()
print(L)	# []

Find List Length

To find the number of items in a list, use len() method.

Example: Find length of a list

L = ['red', 'green', 'blue']
print(len(L))	# 3

Check if item exists in a list

To determine whether a value is or isn’t in a list, you can use in and not in operators with if statement.

Example: Check for presence/absence of an item in a list

# Check for presence
L = ['red', 'green', 'blue']
if 'red' in L:
    print('yes')
# Check for absence
L = ['red', 'green', 'blue']
if 'yellow' not in L:
    print('yes')

Iterate through a List

The most common way to iterate through a list is with a for loop.

Example: Print each item in a List

L = ['red', 'green', 'blue']
for item in L:
    print(item)
# Output: red green blue

This works well if you only need to read the items of the list.

But if you want to update them, you need the indexes. A common way to do that is to combine the range() and len() functions.

Example: Loop through the list and double each item

L = [1, 2, 3, 4]
for i in range(len(L)):
    L[i] = L[i] * 2

print(L)	# [2, 4, 6, 8]

Python List Methods

Python has a set of built-in methods that you can call on list objects.

Python List Methods
MethodDescription
append()Adds an item to the end of the list
insert()Inserts an item at a given position
extend()Extends the list by appending all the items from the iterable
remove()Removes first instance of the specified item
pop()Removes the item at the given position in the list
clear()Removes all items from the list
copy()Returns a shallow copy of the list
count()Returns the count of specified item in the list
index()Returns the index of first instance of the specified item
reverse()Reverses the items of the list in place
sort()Sorts the items of the list in place

Built-in Functions with List

Python also has a set of built-in functions that you can use with list objects.

Python Built-in Functions with List
MethodDescription
all()Returns True if all list items are true
any()Returns True if any list item is true
enumerate()Takes a list and returns an enumerate object
len()Returns the number of items in the list
list()Converts an iterable (tuple, string, set etc.) to a list
max()Returns the largest item of the list
min()Returns the smallest item of the list
sorted()Returns a sorted list
sum()Sums items of the list