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
- False
- Yes, unlike strings, lists can consist of any type of Python data.
- True
- Lists are heterogeneous, meaning they can have different types of data.
9.1Q-1: A list can contain only integer items.
- [4, 2, 8, 6, 5, 999]
- You cannot concatenate a list with an integer.
- Error, you cannot concatenate a list with an integer.
- Yes, in order to perform concatenation you would need to write alist+[999]. You must have two lists.
9.1Q-2: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist = alist + 999
print(alist)
- [ [ ], 3.14, False]
- Yes, the slice starts at index 4 and goes up to and including the last item.
- [ [ ], 3.14]
- By leaving out the upper bound on the slice, we go up to include the last item.
- [ [56, 57, "dog"], [ ], 3.14, False]
- Index values start at 0.
9.1Q-3: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[4:])
- 6
- Concatenation does not add the lengths of the lists.
- [1, 2, 3, 4, 5, 6]
- Concatenation does not reorder the items.
- [1, 3, 5, 2, 4, 6]
- Yes, a new list with all the items of the first list followed by all those from the second.
- [3, 7, 11]
- Concatenation does not add the individual items.
9.1Q-4: What is printed by the following statements?
alist = [1, 3, 5]
blist = [2, 4, 6]
print(alist + blist)
- 9
- Repetition does not multiply the lengths of the lists. It repeats the items.
- [1, 1, 1, 3, 3, 3, 5, 5, 5]
- Repetition does not repeat each item individually.
- [1, 3, 5, 1, 3, 5, 1, 3, 5]
- Yes, the items of the list are repeated 3 times, one after another.
- [3, 9, 15]
- Repetition does not multiply the individual items.
9.1Q-5: What is printed by the following statements?
alist = [1, 3, 5]
print(alist * 3)
- True
- Yes, 3.14 is an item in the list alist.
- False
- There are 7 items in the list, 3.14 is one of them.
9.1Q-6: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(3.14 in alist)
- True
- in returns True for top level items only. 57 is in a sublist.
- False
- Yes, 57 is not a top level item in alist. It is in a sublist.
9.1Q-7: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(57 in alist)
- 4
- len returns the actual number of items in the list, not the maximum index value.
- 5
- Yes, there are 5 items in this list.
9.1Q-8: What is printed by the following statements?
alist = [3, 67, "cat", 3.14, False]
print(len(alist))
- 7
- Yes, there are 7 items in this list even though two of them happen to also be lists.
- 8
- len returns the number of top level items in the list. It does not count items in sublists.
9.1Q-9: What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(len(alist))
© Copyright 2024 GS Ng.