When to not use lists in Python?

A list is an ordered collection of values. It can contain various types of values. A list is a mutable container. This means that we can add values, delete values, or modify existing values.

Python list represents a mathematical concept of a finite sequence. Values of a list are called items or elements of the list. A list can contain the same value multiple times. Each occurrence is considered a distinct item.

Python simple list

List elements can be accessed by their index. The first element has index 0, the last one has index -1.

#!/usr/bin/python

# simple.py

nums = [1, 2, 3, 4, 5]

print(nums[0])
print(nums[-1])
print(nums)

This is a simple list having five elements. The list is delimited by square brackets

nums = [1, 2, 3, 4, 5]
51. The elements of a list are separated by a comma character. The contents of a list are printed to the console.

nums = [1, 2, 3, 4, 5]

The right side of the assignment is a Python list literal. It creates a list containing five elements.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]

Lists can contain elements of various data types.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)

In the example, we create an objects list. It contains numbers, a boolean value, another list, a string, a tuple, a custom object, and a dictionary.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]

Sometimes we need to initialize a list in advance to have a particular number of elements.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)

In this example we initialize two lists using a list comprehension and a * operator.

n1 = [0 for i in range(15)]
n2 = [0] * 15

These two lists are initialized to fifteen zeros.

n1[0:10] = [10] * 10

First ten values are replaced with 10s.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]

Python list function

The

nums = [1, 2, 3, 4, 5]
52 function creates a list from an iterable object. An iterable may be either a sequence, a container that supports iteration, or an iterator object. If no parameter is specified, a new empty list is created.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))

In the example, we create an empty list, a list from a tuple, a string, and another list.

nums = [1, 2, 3, 4, 5]
0

These are two ways to create an empty list.

nums = [1, 2, 3, 4, 5]
1

The line prints

nums = [1, 2, 3, 4, 5]
53. This confirms that
nums = [1, 2, 3, 4, 5]
54 and
nums = [1, 2, 3, 4, 5]
55 are equal.

nums = [1, 2, 3, 4, 5]
2

We create a list from a Python tuple.

nums = [1, 2, 3, 4, 5]
3

This line produces a list from a string.

nums = [1, 2, 3, 4, 5]
4

Finally, we create a copy of a list of strings.

nums = [1, 2, 3, 4, 5]
5

The following code shows some basic list operations.

nums = [1, 2, 3, 4, 5]
6

We define two lists of integers. We use a few operators on these lists.

nums = [1, 2, 3, 4, 5]
7

The contents of the lists are compared with the

nums = [1, 2, 3, 4, 5]
56 operator. The line prints
nums = [1, 2, 3, 4, 5]
57 since the elements are different.

nums = [1, 2, 3, 4, 5]
8

The

nums = [1, 2, 3, 4, 5]
58 and
nums = [1, 2, 3, 4, 5]
59 lists are added to form a new list. The new list has all elements of both the lists.

nums = [1, 2, 3, 4, 5]
9

We use the multiplication operator on the list. It repeats the elements n times; three times in our case.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
0

We use the

nums = [1, 2, 3, 4, 5]
60 operator to find out whether the value is present in the list. It returns a boolean
nums = [1, 2, 3, 4, 5]
53 or
nums = [1, 2, 3, 4, 5]
57.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
1

Python sequence functions

Sequence functions can be used on any sequence types, including lists.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
2

In the example above, we have four functions:

nums = [1, 2, 3, 4, 5]
63,
nums = [1, 2, 3, 4, 5]
64,
nums = [1, 2, 3, 4, 5]
65, and
nums = [1, 2, 3, 4, 5]
66.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
3

The

nums = [1, 2, 3, 4, 5]
63 function returns the size of the list. The number of elements of the list.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
4

The

nums = [1, 2, 3, 4, 5]
64 and
nums = [1, 2, 3, 4, 5]
65 functions return the maximum and the minimum of the list.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
5

The

nums = [1, 2, 3, 4, 5]
66 function calculates the sum of the numbers of the
nums = [1, 2, 3, 4, 5]
71 list.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
6

This section will show how elements are added to a Python list.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
7

We have three methods to add new elements to a list:

nums = [1, 2, 3, 4, 5]
72,
nums = [1, 2, 3, 4, 5]
73, and
nums = [1, 2, 3, 4, 5]
74.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
8

An empty list is created.

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
9

The

nums = [1, 2, 3, 4, 5]
72 method adds an item at the end of the list; we append two strings.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
0

The

nums = [1, 2, 3, 4, 5]
73 method places an element at a specific position indicated by the index number. The
nums = [1, 2, 3, 4, 5]
77 string is inserted at the first position, the
nums = [1, 2, 3, 4, 5]
78 string at the third position. Note that list index numbers start from zero.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
1

The

nums = [1, 2, 3, 4, 5]
74 method adds a sequence of values to the end of a list. In our case two strings of a Python tuple are appended at the end of our list.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
2

Python list IndexError

The

nums = [1, 2, 3, 4, 5]
80 is raised when a list subscript is out of range.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
3

In the script we have defined a list of five integers. These elements have indexes 0, 1, 2, 3, and 4. Using a bigger index leads to an error.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
4

Index 6 is out of range for our list. An

nums = [1, 2, 3, 4, 5]
80 is thrown.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
5

We catch the error using the

nums = [1, 2, 3, 4, 5]
82 clause. In the body of the clause, we print the error message.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
6

If an index of a tuple is not a plain integer a

nums = [1, 2, 3, 4, 5]
83 is thrown.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
7

This example throws a

nums = [1, 2, 3, 4, 5]
83.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
8

A list index must be an integer. Other types end in error.

#!/usr/bin/python

# various_types.py

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print(objects)
9

In the except block, we print the name of the file, where the exception has occurred and the message string.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
0

Previously we have added items to a list. Now we be removing them from a list.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
1

The

nums = [1, 2, 3, 4, 5]
85 method removes and returns an element with a specified index or the last element if the index number is not given. The
nums = [1, 2, 3, 4, 5]
86 method removes a particular item from a list.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
2

We take away the element which has index 3. The

nums = [1, 2, 3, 4, 5]
85 method returns the name of the removed element; it is printed to the console.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
3

The last element from the list, namely

nums = [1, 2, 3, 4, 5]
88 string, is removed from the list.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
4

This line removes a

nums = [1, 2, 3, 4, 5]
89 string from the
nums = [1, 2, 3, 4, 5]
90 list.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
5

From the ouput of the script we can see the effects of the described methods.

A

nums = [1, 2, 3, 4, 5]
91 keyword can be used to delete list elements as well.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
6

We have a list of strings. We use the

nums = [1, 2, 3, 4, 5]
91 keyword to delete list elements.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
7

We remove the second string from the list. It is the

nums = [1, 2, 3, 4, 5]
89 string.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
8

We can delete only existing elements. If we uncomment the code line, we receive an

nums = [1, 2, 3, 4, 5]
80 message.

$ ./various_types.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3),
    <__main__.Being instance at 0x7f653577f6c8>, {}]
9

Here we remove all the remaining elements from the list. The

nums = [1, 2, 3, 4, 5]
95 characters refer to all items of a list.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
0

In the next example we be modifying list elements.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
1

In the example we modify the third element of the langs list twice.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
2

One way to modify an element is to remove it and place a different element at the same position.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
3

The other method is more straightforward. We assign a new element at a given position. Now there is

nums = [1, 2, 3, 4, 5]
96 string at the third position again.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
4

There are several ways how we can copy a list in Python. We will mention a few of them.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
5

We have a list of three strings. We make a copy of the list seven times.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
6

We import the

nums = [1, 2, 3, 4, 5]
97 module which has two methods for copying.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
7

A list is copied using the slice syntax.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
8

The

nums = [1, 2, 3, 4, 5]
52 function creates a copy of a list when it takes a list as a parameter.

#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print(n1)
print(n2)

n1[0:10] = [10] * 10

print(n1)
9

The

nums = [1, 2, 3, 4, 5]
97 method produces a shallow copy of a list. The
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
00 produces a deep copy of a list.

n1 = [0 for i in range(15)]
n2 = [0] * 15
0

A copy of a string is created using list comprehension.

n1 = [0 for i in range(15)]
n2 = [0] * 15
1

A copy created by a

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
01 loop.

n1 = [0 for i in range(15)]
n2 = [0] * 15
2

The

nums = [1, 2, 3, 4, 5]
74 method can be used to create a copy too.

n1 = [0 for i in range(15)]
n2 = [0] * 15
3

Seven copies of a string list were created using different techniques.

Python indexing list elements

Elements in a Python list can be accessed by their index. Index numbers are integers; they start from zero. Indexes can be negative; negative indexes refer to elements from the end of the list. The first item in a list has index 0, the last item has -1.

n1 = [0 for i in range(15)]
n2 = [0] * 15
4

We can access an element of a list by its index. The index is placed between the square brackets

nums = [1, 2, 3, 4, 5]
51 after the name of the list.

n1 = [0 for i in range(15)]
n2 = [0] * 15
5

These three lines print the first, the last and the last but one item of the list.

n1 = [0 for i in range(15)]
n2 = [0] * 15
6

The two lines print the fourth and sixth element of the list.

n1 = [0 for i in range(15)]
n2 = [0] * 15
7

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
04 method looks for a particular element and returns its lowest index. The start and end are optional parameters that limit the search to given boundaries.

n1 = [0 for i in range(15)]
n2 = [0] * 15
8

A code example with the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
05 method.

n1 = [0 for i in range(15)]
n2 = [0] * 15
9

These two lines print the indexes of the leftmost 1, 2 values of the n list.

n1[0:10] = [10] * 10
0

Here we search for values 1 and 2 after specified indexes.

n1[0:10] = [10] * 10
1

Here we search for value 1 between values with indexes 2 and 5.

n1[0:10] = [10] * 10
2

List slicing is an operation that extracts certain elements from a list and forms them into another list. Possibly with different number of indices and different index ranges.

The syntax for list slicing is as follows:

n1[0:10] = [10] * 10
3

The start, end, step parts of the syntax are integers. Each of them is optional. They can be both positive and negative. The value having the end index is not included in the slice.

n1[0:10] = [10] * 10
4

We create four slices from a list of eight integers.

n1[0:10] = [10] * 10
5

The first slice has values with indexes 1, 2, 3, and 4. The newly formed list is [2, 3, 4, 5].

n1[0:10] = [10] * 10
6

If the start index is omitted then a default value is assumed, which is 0. The slice is [1, 2, 3, 4, 5].

n1[0:10] = [10] * 10
7

If the end index is omitted, the -1 default value is taken. In such a case a slice takes all values to the end of the list.

n1[0:10] = [10] * 10
8

Even both indexes can be left out. This syntax creates a copy of a list.

n1[0:10] = [10] * 10
9

The third index in a slice syntax is the step. It allows us to take every n-th value from a list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
0

We form four new lists using the step value.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
1

Here we create a slice having every second element from the n list, starting from the second element, ending in the eighth element. The new list has the following elements: [2, 4, 6, 8].

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
2

Here we build a slice by taking every second value from the beginning to the end of the list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
3

This creates a copy of a list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
4

The slice has every third element, starting from the second element to the end of the list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
5

Indexes can be negative numbers. Negative indexes refer to values from the end of the list. The last element has index -1, the last but one has index -2 etc. Indexes with lower negative numbers must come first in the syntax. This means that we write [-6, -2] instead of [-2, -6]. The latter returns an empty list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
6

In this script, we form five lists. We also use negative index numbers.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
7

The first line returns [5, 6, 7], the second line returns an empty list. Lower indexes must come before higher indexes.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
8

This creates a reversed list.

$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0]
9

The above mentioned syntax can be used in assignments. There must be an iterable on the right side of the assignment.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
0

We have a list of eight integers. We use the slice syntax to replace the elements with new values.

Python loop list

This section will point out three basic ways to traverse a list in Python.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
1

The first one is the most straightforward way to traverse a list.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
2

We have a numerical list. There are five integers in the list.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
3

Using the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
01 loop, we go through the list one by one and print the current element to the console.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
4

This is the output of the script. The integers are printed to the terminal.

The second example is a bit more verbose.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
5

We are traversing the list using the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
07 loop.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
6

First, we need to define a counter and find out the size of the list.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
7

With the help of these two numbers, we go through the list and print each element to the terminal.

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
08 built-in function gives us both the index and the value of a list in a loop.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
8

In the example, we print the values and the indexes of the values.

#!/usr/bin/python

# list_fun.py

a = []
b = list()

print(a == b)

print(list((1, 2, 3)))
print(list("ZetCode"))
print(list(['Ruby', 'Python', 'Perl']))
9

Sometimes it is important to count list elements. For this, Python has the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
09 method.

nums = [1, 2, 3, 4, 5]
00

In this example, we count the number of occurrences of a few numbers in the

nums = [1, 2, 3, 4, 5]
71 list.

nums = [1, 2, 3, 4, 5]
01

We have a list of integer numbers. Integers 1 and 4 are present multiple times.

nums = [1, 2, 3, 4, 5]
02

Using the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
09 method, we find out the occurrence of 4, 1, 2, and 6 numbers.

nums = [1, 2, 3, 4, 5]
03

Number 4 is present 3 times, 1 twice, 2 once, and 6 is not present in the list.

It is possible to nest lists into another lists. With a nested list a new dimension is created. To access nested lists one needs additional square brackets

nums = [1, 2, 3, 4, 5]
51.

nums = [1, 2, 3, 4, 5]
04

In the example, we have three nested lists having two elements each.

nums = [1, 2, 3, 4, 5]
05

Three nested lists of the nums list are printed to the console.

nums = [1, 2, 3, 4, 5]
06

Here we print the two elements of the first nested list. The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
13 refers to the first nested list; the
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
14 refers to the first element of the first nested list, namely 1.

nums = [1, 2, 3, 4, 5]
07

The line prints 3. Each nested list is counted as one element. Its inner elements are not taken into account.

nums = [1, 2, 3, 4, 5]
08

The second example has additional dimensions.

nums = [1, 2, 3, 4, 5]
09

In the example, the [5, 6] list is nested into [3, 4, ...] list, the [3, 4, [4, 6]] is nested into the [1, 2, ...] list which is finally an element of the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
15 list.

nums = [1, 2, 3, 4, 5]
10

These three lines print the nested lists to the console.

nums = [1, 2, 3, 4, 5]
11

Here three elements are accessed. Additional square brackets

nums = [1, 2, 3, 4, 5]
51 are needed when referring to inner lists.

nums = [1, 2, 3, 4, 5]
12

In this section we sort list elements. Python has a built-in list method

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
17 and
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
18 function for doing sorting.

nums = [1, 2, 3, 4, 5]
13

In the code example, we have a list of unsorted integers. We sort the elements using the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
17 method. The method sorts the elements in-place; the original list is modified.

nums = [1, 2, 3, 4, 5]
14

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
17 method sorts the elements in ascending order.

nums = [1, 2, 3, 4, 5]
15

With the reverse parameter set to

nums = [1, 2, 3, 4, 5]
53, the list is sorted in a descending order.

nums = [1, 2, 3, 4, 5]
16

In the output we can see the original list, the sorted list in ascending and descending orders.

If we do not want to change the original list, we can use the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
18 function. This function creates a new sorted list.

nums = [1, 2, 3, 4, 5]
17

In the example, we use the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
18 function to sort the elements of a list.

nums = [1, 2, 3, 4, 5]
18

From the output of the script we can see that the original list is not modified.

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
17 method has an optional
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
25 parameter. The parameter specifies a function to be called on each list element prior to making comparisons.

nums = [1, 2, 3, 4, 5]
19

The example produces a case-sensitive and case-insensitive string comparison.

nums = [1, 2, 3, 4, 5]
20

To create a case-insensitive comparison, we add the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
26 function to the
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
25 parameter.

nums = [1, 2, 3, 4, 5]
21

We need to do additional work if we want to sort Unicode strings.

nums = [1, 2, 3, 4, 5]
22

We have a list of six unicode strings. We change the locale settings to sort the strings according to current language option.

nums = [1, 2, 3, 4, 5]
23

We import the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
28 module and the
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
29 conversion function.

nums = [1, 2, 3, 4, 5]
24

This is a list of six strings. The strings are in Slovak language and have some diacritical marks. They play role in sorting the characters correctly.

nums = [1, 2, 3, 4, 5]
25

We set the locale settings for the Slovak language.

nums = [1, 2, 3, 4, 5]
26

We sort the list. The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
30 compares two strings according to the current
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
31 setting. The
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
29 function transform an
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
33 comparison function to a key-function.

nums = [1, 2, 3, 4, 5]
27

We print the sorted words to the console.

nums = [1, 2, 3, 4, 5]
28

The elements were correctly sorted. The specifics of the Slovak alphabet were taken into account.

We can reverse elements in a list in a few ways in Python. Reversing elements should not be confused with sorting in a reverse way.

nums = [1, 2, 3, 4, 5]
29

In the example, we have three identical string lists. We reverse the elements in three different ways.

nums = [1, 2, 3, 4, 5]
30

The first way is to use the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
34 method.

nums = [1, 2, 3, 4, 5]
31

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
35 function returns a reverse iterator. We use the iterator in a for loop and create a new reversed list.

nums = [1, 2, 3, 4, 5]
32

The third way is to reverse the list using the slice syntax, where the step parameter is set to -1.

nums = [1, 2, 3, 4, 5]
33

All the three lists were reversed OK.

Python list comprehension

A list comprehension is a syntactic construct which creates a list based on existing list. The syntax was influenced by mathematical notation of sets. The Python syntax was inspired by the Haskell programming language.

nums = [1, 2, 3, 4, 5]
34

The above pseudo code shows the syntax of a list comprehension. A list comprehension creates a new list. It is based on an existing list. A for loop goes through the sequence. For each loop an expression is evaluated if the condition is met. If the value is computed it is appended to the new list. The condition is optional.

List comprehensions provide a more concise way to create lists in situations where

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
36 and
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
37 and/or nested loops could be used.

nums = [1, 2, 3, 4, 5]
35

In the example we have defined a list of numbers. With the help of the list comprehension, we create a new list of numbers that cannot be divided by 2 without a remainder.

nums = [1, 2, 3, 4, 5]
36
nums = [1, 2, 3, 4, 5]
37

Here we have the list comprehension. In the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
38 loop each element of a list is taken. Then a
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
39 condition is tested. If the condition is met, an expression is evaluated. In our case the expression is a pure
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
40 which takes the element as it is. Finally, the element is appended to the list.

nums = [1, 2, 3, 4, 5]
38

he numbers in a list cannot be divided by 2, without a remainder.

In the second example we compare a list comprehension to a traditional for loop.

nums = [1, 2, 3, 4, 5]
39

In the example we have a string. We want to create a list of the ASCII integer codes of the letters of the string.

nums = [1, 2, 3, 4, 5]
40

We create such a list with the for loop.

nums = [1, 2, 3, 4, 5]
41

Here the same is produced using a list comprehension. Note that the if condition was omitted. It is optional.

nums = [1, 2, 3, 4, 5]
42

Check Python list comprehensions for more details.

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
36 and
$ ./simple.py
1
5
[1, 2, 3, 4, 5]
37 functions are mass functions that work on all list items. They are part of the functional programming built into the Python language.

Today, it is recommended to use list comprehensions instead of these functions where possible.

nums = [1, 2, 3, 4, 5]
43

The

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
36 function applies a particular function to every element of a list.

nums = [1, 2, 3, 4, 5]
44

This is the definition of the function used by the

$ ./simple.py
1
5
[1, 2, 3, 4, 5]
37 function. It returns
nums = [1, 2, 3, 4, 5]
53 or
nums = [1, 2, 3, 4, 5]
57. Functions that return a boolean value are called predicates.

What are the disadvantages of using list Python?

The list has the limitation that one can only append at the end. But, in real life, there are situations that a developer has to add items at the starting of the existing list which becomes difficult in the list. Sometimes the rotation of items within the list is also required which is also a limitation in the list.

When should I use a set instead of a list in Python?

Advantages of a Python Set Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.

What can I use instead of a list in Python?

Here are a few alternatives that are worthy of consideration..
Tuples. Tuples share many key similarities with lists. ... .
Numpy Arrays. Unlike lists, numpy arrays are not a built-in data structure. ... .
Sets. Sets are, in my opinion, the most overlooked data structure in Python..

Are Python lists inefficient?

A Python list is actually an array of pointers (at least in the reference implementation). That is part of where the inefficiency comes from. The other part is that Python normally uses duck-typing, so you can not tell if an operation is going to work on a list element until you try it.