Chapter 9 Lists

9.1 Lists - A Mutable Sequential TypeΒΆ

The sequential type is the most commonly used container type in programming, and mutability offers list versatility in their use. As the result, lists are one of the most powerful tools in Python programming.

The list type is the third sequential type introduced in this book. It is a container type, and can be regarded as a mutable version of tuples. A list literal consists of a comma-separated list of objects and identifiers, enclosed in a pair of square brackets.

>>> type ([1 ,2 ,3])
<class 'list'>
>>> l=[1] # one item
>>> type(l)
<class 'list'>
>>> l [1]
>>> x='a'
>>> l=[x, True, None] # heterogeneous list
>>> type(l)
<class 'list'>
>>> l
['a', True, None]

List literals are different from tuple literals only in the enclosing square brackets (i.e. [ ] instead of ( )). As shown by the example above, unlike tuple literals, no comma is needed in a list literal that contains only one item, because unlike parentheses, the use of square brackets is unambiguous.

Lsit concatenation. Again, as with strings, the + operator concatenates lists. Similarly, the * operator repeats the items in a list a given number of times.

It is important to see that these operators create new lists from the elements of the operand lists. If you concatenate a list with 2 items and a list with 4 items, you will get a new list with 6 items (not a list with two sublists). Similarly, repetition of a list of 2 items 4 times will give a list with 8 items.

One way to make this more clear is to run a part of this example in codelens. As you step through the code, you will see the variables being created and the lists that they refer to. Pay particular attention to the fact that when newlist is created by the statement newlist = fruit + numlist, it refers to a completely new list formed by making copies of the items from fruit and numlist. You can see this very clearly in the codelens object diagram. The objects are different.

Activity: CodeLens 2 (nine1Example1)

List id. In Python, every object has a unique identification tag. Likewise, there is a built-in function that can be called on any object to return its unique id. The function is appropriately called id and takes a single parameter, the object that you are interested in knowing about. You can see in the example below that a real id is usually a very large integer value (corresponding to an address in memory).

>>> alist = [4, 5, 6]
>>> id(alist)
4300840544
>>>

List Operators. The list type supports all the operations of strings and tuples, including in, not in, getitem and getslice. In addition, the len function can also be applied to lists.

>>> l=[1, 'a', False]
>>> 'a' in l
True
>>> 'b' in l
False
>>> 1 not in l
False
>>> 2 not in l
True
>>> l[0] #getitem
1
>>> l[0:2] #getslice
[1, 'a']
>>> l[-1]
False
>>> l[-2:]
['a', False]
>>> len(l)
3
>>> len ([]) # empty list
0

Conversion Between Lists and Other Types. A list object can be converted to a string, a Boolean object, or a tuple object. However, it cannot be converted to numbers. Similar to tuples, the string conversion of a list object is its literal form.

>>> x='a'
>>> y=1
>>> z=True
>>> l=[x, y, z]
>>> str(l)
"['a', 1, True]"
>>> int(l) # cannot be converted numbers
Traceback (most recent call last):
   File "<stdin >", line 1, in <module >
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Similar to the cases of tuples and strings, the Boolean conversion of a list is False only when the list is empty, and True otherwise.

>>> bool ([])
False
>>> bool ([1 ,2 ,3])
True
>>> l=[None]
>>> bool(l)
True

The tuple conversion of a list object is a tuple object that contains exactly the same elements in the same order.

>>> l=[1, 'abc', None]
>>> t=tuple(l)
>>> t
(1, 'abc', None)

On the opposite direction, string and tuple objects can be converted into list objects. However, Boolean or number objects cannot be converted into list objects. Similar to the tuple conversion, the list conversion of a string is a list that consists of all the characters in the string, each as a list item, in their original order. Conversion from tuples to lists is the reverse operation to the conversion from lists to tuples.

>>> l=[1, 'abc', None]
>>> t=tuple(l)
>>> t
(1, 'abc', None)
>>> list("hello!")
['h', 'e', 'l', 'l', 'o', '!']
>>> list((1, 7.5, 1, 'abc', True, None))
[1, 7.5, 1, 'abc', True, None]
>>> list(True) # cannot be converted from Boolean objects
Traceback (most recent call last):
   File "<stdin >", line 1, in <module>
TypeError: 'bool ' object is not iterable
>>> list (1.0) # neither numbers
Traceback (most recent call last):
   File "<stdin >", line 1, in <module>
TypeError: 'float ' object is not iterable

Check your understanding

© Copyright 2024 GS Ng.

Next Section - 9.2 List Mutation