Easy Tutorial
❮ Python Stdlib Python Func Number Random ❯

Python3 List

Sequences are the most fundamental data structures in Python.

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

Python has 6 built-in sequence types, but the most common 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 to determine the length of a sequence and to find the maximum and minimum elements.

Lists are the most commonly used data type in Python and can appear as comma-separated values within square brackets.

The items in a list do not need to be of the same type.

To create a list, simply enclose comma-separated different items within square brackets. For example:

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

Accessing Values in Lists

Like string indices, list indices start at 0, with the second index being 1, and so on.

Lists can be sliced and combined using their indices.

Example

#!/usr/bin/python3

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

Output:

red
green
blue

Indices can also start from the end of the list, with the last element's index being -1, the second to last being -2, and so on.

Example

#!/usr/bin/python3

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

Output:

black
white
yellow

You can access values in lists using subscript indices, and you can also slice characters using square brackets [], as shown below:

Example

#!/usr/bin/python3

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

Output:

[10, 20, 30, 40]

Using negative index values for slicing:

Example

#!/usr/bin/python3

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

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

Output:

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

Updating Lists

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

Example (Python 3.0+)

#!/usr/bin/python3

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

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

list1 = ['Google', 'tutorialpro', 'Taobao']
list1.append('Baidu')
print("The updated list is: ", list1)

Note: We will discuss the use of the append() method in the next chapter.

Output:

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

Deleting List Elements

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

Example (Python 3.0+)

#!/usr/bin/python3

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

print("Original list: ", list)
del list[2]
print("After deleting the third element: ", list)

Output:

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

Original list: ['Google', 'tutorialpro', 1997, 2000] Remove the third element: ['Google', 'tutorialpro', 2000]

Note: We will discuss the use of the remove() method in the following sections.


Python List Script Operators

Lists support operators similar to strings for concatenation and repetition. The + operator is used to combine lists, and the * operator is used to repeat lists.

Here are some examples:

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 existence check
for x in [1, 2, 3]: print(x, end=" ") 1 2 3 Iteration

Python List Slicing and Concatenation

Python lists support slicing similar to strings. Here are some examples:

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

Operations:

Python Expression Result Description
L[2] 'Taobao' Access the third element
L[-2] 'tutorialpro' Access the second-to-last element from the right
L[1:] ['tutorialpro', 'Taobao'] Output all elements starting from the second
>>> L = ['Google', 'tutorialpro', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'tutorialpro'
>>> L[1:]
['tutorialpro', '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]
>>>

Nested Lists

Nested lists involve creating lists within lists, 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 Comparisons

List comparisons require the eq method from the operator module (see Python operator module for details):

# 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:

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

Python List Functions & Methods

Python includes the following functions:

Number Function
1 len(list) <br>List length
2 max(list) <br>Return the maximum element
3 min(list) <br>Return the minimum element
4 list(seq) <br>Convert a tuple to a list

Python includes the following methods:

Number Method
1 list.append(obj) <br>Append an object to the end of the list
2 list.count(obj) <br>Count the occurrences of an element in the list
3 list.extend(seq) <br>Add multiple values from another sequence to the end of the list (extend the original list with a new list)
4 list.index(obj) <br>Find the index of the first occurrence of a value in the list
5 list.insert(index, obj) <br>Insert an object into the list at a specified index
6 list.pop([index=-1]) <br>Remove an element from the list (default is the last element) and return its value
7 list.remove(obj) <br>Remove the first occurrence of a value from the list
8 list.reverse() <br>Reverse the elements of the list
9 list.sort( key=None, reverse=False) <br>Sort the list in place
10 list.clear() <br>Clear the list
11 list.copy() <br>Copy the list
❮ Python Stdlib Python Func Number Random ❯