Skip to content

Python3 Lists

Sequences are the most basic data structure in Python.

Each value in a sequence has a corresponding position value, called an index, with the first index being 0, the second being 1, and so on.

Python has 6 built-in types for sequences, but the most common ones are lists and tuples.

Operations that can be performed on lists include indexing, slicing, adding, multiplying, and checking membership.

Additionally, Python has built-in methods for determining the length of a sequence and finding the largest and smallest elements.

Lists are the most commonly used Python data type, and they can appear as a comma-separated list of values enclosed in square brackets.

List items do not need to be of the same type.

To create a list, simply enclose comma-separated data items in square brackets. As shown below:

list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']

Like string indices, list indices start at 0, the second is 1, and so on.

You can access, slice, and combine lists using index operations.

#!/usr/bin/python3

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[0] )
print( list[1] )
print( list[2] )

Output of the above example:

red
green
blue

Indices can also start from the end, with the last element having an index of -1, the second to last -2, and so on.

#!/usr/bin/python3

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[-1] )
print( list[-2] )
print( list[-3] )

Output of the above example:

black
white
yellow

Use subscript indices to access values in a list, and you can also use square brackets [] to slice characters, as shown below:

#!/usr/bin/python3

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])

Output of the above example:

[10, 20, 30, 40]

Slicing using negative indices:

#!/usr/bin/python3

list = ['Google', 'Runoob', "Zhihu", "Taobao", "Wiki"]

# Read the second element
print ("list[1]: ", list[1])
# Slice from the second element (inclusive) to the second-to-last element (exclusive)
print ("list[1:-2]: ", list[1:-2])

Output of the above example:

list[1]:  Runoob
list[1:-2]:  ['Runoob', 'Zhihu']

You can modify or update list items, and you can also use the append() method to add list items, as shown below:

#!/usr/bin/python3

list = ['Google', 'Runoob', 1997, 2000]

print ("The third element is: ", list[2])
list[2] = 2001
print ("The updated third element is: ", list[2])

list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("Updated list: ", list1)

Note: We will discuss the append() method in the following chapters.

Output of the above example:

The third element is:  1997
The updated third element is:  2001
Updated list:  ['Google', 'Runoob', 'Taobao', 'Baidu']

You can use the del statement to delete elements from a list, as shown in the example below:

#!/usr/bin/python3
 
list = ['Google', 'Runoob', 1997, 2000]
 
print ("Original list: ", list)
del list[2]
print ("After deleting the third element: ", list)

Output of the above example:

Original list:  ['Google', 'Runoob', 1997, 2000]
After deleting the third element:  ['Google', 'Runoob', 2000]

Note: We will discuss the remove() method in the following chapters.


List operators + and * work similarly to strings. The + sign is used to combine lists, and the * sign is used to repeat lists.

As shown below:

Python Expression Result Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Element exists in list
for x in [1, 2, 3]: print(x, end=“ “) 1 2 3 Iteration

Python list slicing is similar to string operations, as shown below:

L=['Google', 'Runoob', 'Taobao']

Operations:

Python Expression Result Description
L[2] ‘Taobao’ Read the third element
L[-2] ‘Runoob’ Read the second-to-last element from the right: count from the right
L[1:] [‘Runoob’, ‘Taobao’] Output all elements starting from the second element
>>> L=['Google', 'Runoob', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Runoob'
>>> L[1:]
['Runoob', 'Taobao']
>>> 

Lists also support concatenation:

>>> squares = [1, 4, 9, 16, 25]
>>> squares += [36, 49, 64, 81, 100]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> 

Using nested lists means creating other lists inside a list, for example:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

List comparison requires importing the eq method from the operator module (see: Python operator module):

# Import the operator module
import operator

a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))

Output of the above code:

operator.eq(a,b):  False
operator.eq(c,b):  True

Python includes the following functions:

No. Function
1 len(list)
Number of list elements
2 max(list)
Returns the maximum value of list elements
3 min(list)
Returns the minimum value of list elements
4 list(seq)
Converts a tuple to a list

Python includes the following methods:

No. Method
1 list.append(obj)
Adds a new object to the end of the list
2 list.count(obj)
Counts the number of occurrences of an element in the list
3 list.extend(seq)
Appends multiple values from another sequence to the end of the list at once (extends the original list with a new list)
4 list.index(obj)
Finds the index position of the first matching item of a value in the list
5 list.insert(index, obj)
Inserts an object into the list
6 list.pop([index=-1])
Removes an element from the list (defaults to the last element) and returns its value
7 list.remove(obj)
Removes the first matching item of a value from the list
8 list.reverse()
Reverses the elements in the list
9 list.sort( key=None, reverse=False)
Sorts the original list
10 list.clear()
Clears the list
11 list.copy()
Copies the list