5.2 Lists

  • Many of the capabilities shown in this section apply to all sequence types.

Creating a List

  • Lists typically store homogeneous data, but may store heterogeneous data.
In [1]:
c = [-45, 6, 0, 72, 1543]
In [2]:
c
Out[2]:
[-45, 6, 0, 72, 1543]

Accessing Elements of a List

  • Reference a list element by writing the list’s name followed by the element’s index enclosed in [] (the subscription operator).

Diagram of a list named c labeled with its element names

In [3]:
c[0]
Out[3]:
-45
In [4]:
c[4]
Out[4]:
1543

Determining a List’s Length

In [5]:
len(c)
Out[5]:
5

Accessing Elements from the End of the List with Negative Indices

  • Lists can be accessed from the end by using negative indices: Diagram of the list c labeled with its negative indices
In [6]:
c[-1]
Out[6]:
1543
In [7]:
c[-5]
Out[7]:
-45

Indices Must Be Integers or Integer Expressions

In [8]:
a = 1
In [9]:
b = 2
In [10]:
c[a + b]
Out[10]:
72

Lists Are Mutable

In [11]:
c[4] = 17
In [12]:
c
Out[12]:
[-45, 6, 0, 72, 17]

Some Sequences Are Immutable

  • Python’s string and tuple sequences are immutable.
In [13]:
s = 'hello'
In [14]:
s[0]
Out[14]:
'h'
In [15]:
s[0] = 'H'
------------------------------------------------------------------------
TypeError                              Traceback (most recent call last)
<ipython-input-15-d6f3b193531a> in <module>
----> 1 s[0] = 'H'

TypeError: 'str' object does not support item assignment

Attempting to Access a Nonexistent Element

  • Index values must be in range.
In [16]:
c[100]
------------------------------------------------------------------------
IndexError                             Traceback (most recent call last)
<ipython-input-16-78fb4de297cc> in <module>
----> 1 c[100]

IndexError: list index out of range

Using List Elements in Expressions

In [17]:
c[0] + c[1] + c[2]
Out[17]:
-39

Appending to a List with +=

  • Lists can grow dynamically to accommodate new items.
In [18]:
a_list = []
In [19]:
for number in range(1, 6):
    a_list += [number]
In [20]:
a_list
Out[20]:
[1, 2, 3, 4, 5]
  • When the left operand of += is a list, the right operand must be an iterable; otherwise, a TypeError occurs.
In [21]:
letters = []
In [22]:
letters += 'Python'
In [23]:
letters
Out[23]:
['P', 'y', 't', 'h', 'o', 'n']

Concatenating Lists with +

  • Can concatenate two lists, two tuples or two strings using + to create a new sequence of the same type.
In [24]:
list1 = [10, 20, 30]
In [25]:
list2 = [40, 50]
In [26]:
concatenated_list = list1 + list2
In [27]:
concatenated_list
Out[27]:
[10, 20, 30, 40, 50]

Using for and range to Access List Indices and Values

In [28]:
for i in range(len(concatenated_list)):  
    print(f'{i}: {concatenated_list[i]}')
0: 10
1: 20
2: 30
3: 40
4: 50
  • We’ll show a safer way to access element indices and values using built-in function enumerate.

Comparison Operators

  • Can compare entire lists element-by-element.
In [29]:
a = [1, 2, 3]
In [30]:
b = [1, 2, 3]
In [31]:
c = [1, 2, 3, 4]
In [32]:
a == b
Out[32]:
True
In [33]:
a == c
Out[33]:
False
In [34]:
a < c
Out[34]:
True
In [35]:
c >= b
Out[35]:
True

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.