Python Tutorial (12) - Lists

Time: Column:Python views:248

Sequence in Python

A sequence is one of the most basic data structures in Python.

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

Python has six built-in types of 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 provides built-in methods for determining the length of a sequence, as well as the largest and smallest elements.

Lists are the most widely used data type in Python. They are collections of comma-separated values enclosed within square brackets.

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

To create a list, simply place a comma-separated set of data items inside 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']

Accessing Values in a List

Just like string indexing, list indices start at 0, the second index is 1, and so on.

You can access, slice, and combine list elements through their indices.

Just like string indexing, list indices start at 0, the second index is 1, and so on.

Example

#!/usr/bin/python3

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

The output of this code is:

red
green
blue


Negative Indexing

Indices can also be negative. The last element has an index of -1, the second-to-last element has an index of -2, and so forth.

LYS%Indices can also be negative. The last element has an index of -1, the second-to-last element has an index of -2, and so forth.

Example

#!/usr/bin/python3

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

The output of this code is:

black
white
yellow


Slicing Lists

In addition to accessing values via indices, you can also slice lists using square brackets.

In addition to accessing values via indices, you can also slice lists using square brackets.

Example

#!/usr/bin/python3

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

The output of this code is:

[10, 20, 30, 40]


Slicing with Negative Indices

You can also use negative indices for slicing:

Example

#!/usr/bin/python3

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

# Accessing the second element
print("list[1]:", list[1])

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

The output of this code is:

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

Updating a List

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

Example (Python 3.0+)

#!/usr/bin/python3

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

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

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

Output of the code:

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

Note: We will discuss the usage of the append() method in the upcoming sections.

Deleting List Elements

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

Example (Python 3.0+)

#!/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 code:

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

Note: We will discuss the usage of the remove() method in the upcoming sections.

Python List Operators

The + and * operators work similarly for lists as they do for strings. The + operator concatenates lists, while the * operator repeats the list.

Here are some examples:

Python ExpressionResultDescription
len([1, 2, 3])3Length of the list
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation of lists
['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']Repetition of list elements
3 in [1, 2, 3]TrueCheck if an element is in the list
for x in [1, 2, 3]: print(x, end=" ")1 2 3Iterating through a list

Python List Slicing and Concatenation

Slicing lists in Python is similar to slicing strings, as shown below:

L = ['Google', 'Runoob', 'Taobao']
Python ExpressionResultDescription
L[2]'Taobao'Access the third element
L[-2]'Runoob'Access the second-to-last element
L[1:]['Runoob', 'Taobao']Access all elements starting from the second element

Example:

>>> L = ['Google', 'Runoob', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Runoob'
>>> L[1:]
['Runoob', 'Taobao']

You can also concatenate lists:

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

A nested list refers to 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

To compare lists, you need to introduce the eq method from the operator module (for more details, see the Python operator module):

Example

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

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

Python List Functions and Methods

Python includes the following functions:

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

Python also includes the following methods:

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