Python3 Lists

Sequences are the most basic data structures in Python.

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

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

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

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

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

The data items in a list do not need to have the same type.

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

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

Accessing Values in a List

Like string indexing, list indices start from0the second index is1and so on.

By using indices, lists can be sliced, combined, and so on.

Example

#!/usr/bin/python3

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

The above example outputs:

red
green
blue

Indexing can also start from the tail, with the last element's index being-1and the one before it being-2and so on.

Example

#!/usr/bin/python3

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

The above example outputs:

black
white
yellow

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

Example

#!/usr/bin/python3

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

The above example outputs:

[10, 20, 30, 40]

Slicing with negative index values:

Example

#!/usr/bin/python3

list = ['Google', 'Example', "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])

The above example outputs:

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

Updating Lists

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

Example (Python 3.0+)

#!/usr/bin/python3

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

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

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

Note:We will discuss in the following chaptersappend()the usage of the method.

The above example outputs:

第三个元素为 :  1997
更新后的第三个元素为 :  2001
更新后的列表 :  ['Google', 'Example', 'Taobao', 'Baidu']

Deleting List Elements

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

Example (Python 3.0+)

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

The above example outputs:

原始列表 :  ['Google', 'Example', 1997, 2000]
删除第三个元素 :  ['Google', 'Example', 2000]

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


Python List Script Operators

The + and * operators for lists are similar to those for strings. The + sign is used to combine lists, and the * sign is used to repeat lists.

As shown below:

Python ExpressionResultDescription
len([1, 2, 3])3Length
[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]TrueWhether the element exists in the list
for x in [1, 2, 3]: print(x, end=" ")1 2 3Iteration

Python List Slicing and Concatenation

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

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

Operation:

Python ExpressionResultDescription
L[2]'Taobao'Read the third element
L[-2]'Example'Read the second-to-last element from the right: count from the right
L[1:]['Example', 'Taobao']Output all elements starting from the second element
>>> L=['Google', 'Example', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Example'
>>> L[1:]
['Example', 'Taobao']
>>>

Lists also support concatenation operations:

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

Using nested lists means creating other lists within 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

List comparison requires importing theoperatormodule'seqmethod (see:Python operator module):

Example

# Import 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))

The above code outputs:

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

Python List Functions & Methods

Python includes the following functions:

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

Python includes the following methods:

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