Lists¶
- A list is a sequential collection of Python data values, where each value is identified by an index.
- The values that make up a list are called its elements.
- Lists are similar to strings, which are ordered collections of characters, except that the elements of a list can have any type and for any one list, the items can be of different types.
- There are several ways to create a new list. The simplest is to enclose the elements in square brackets (
[
and]
).
vocabulary = ["iteration", "selection", "control"]
numbers = [17, 123]
empty = []
mixedlist = ["hello", 2.0, 5*2, [10, 20]]
print(numbers)
print(mixedlist)
newlist = [ numbers, vocabulary ]
print(newlist)
(chp09_01)
- The function
len
returns the length of a list (the number of items in the list). - Sublists are considered to be a single item when counting the length of the list.
alist = ["hello", 2.0, 5, [10, 20]]
print(len(alist))
print(len(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]))
(chp09_01a)
- The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string.
- Negative index values will locate items from the right instead of from the left.
numbers = [17, 123, 87, 34, 66, 8398, 44]
print(numbers[2])
print(numbers[9 - 8])
print(numbers[-2])
print(numbers[len(numbers) - 1])
(chp09_02)
in
andnot in
are boolean operators that test membership in a sequence. We used them previously with strings and they also work here.
fruit = ["apple", "orange", "banana", "cherry"]
print("apple" in fruit)
print("pear" in fruit)
(chp09_4)
- Again, as with strings, the
+
operator concatenates lists. - Similarly, the
*
operator repeats the items in a list a given number of times.
fruit = ["apple", "orange", "banana", "cherry"]
print([1, 2] + [3, 4])
print(fruit + [6, 7, 8, 9])
print([0] * 4)
print([1, 2, ["hello", "goodbye"]] * 2)
numlist = [6, 7]
newlist = fruit + numlist
zeros = [0] * 4
print(newlist)
print(zeros)
(chp09_5)
- The slice operation we saw with strings also work on lists.
- Remember that the first index is the starting point for the slice and the second number is one index past the end of the slice.
a_list = ['a', 'b', 'c', 'd', 'e', 'f']
print(a_list[1:3])
print(a_list[:4])
print(a_list[3:])
print(a_list[:])
(chp09_6)
Lists are Mutable¶
- Unlike strings, lists are mutable.
- This means we can change an item in a list by accessing it directly as part of the assignment statement.
- Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.
bananavariable = "banana"
#bananavariable[O]= 'c'
fruit = ["banana", "apple", "cherry"]
print(fruit)
fruit[0] = "pear"
fruit[-1] = "orange"
print(fruit)
(ch09_7)
List Deletion¶
- Using slices to delete list elements can be awkward and therefore error-prone.
- The
del
statement removes an element from a list by using its position.
a = ['one', 'two', 'three']
del a[1]
print(a)
alist = ['a', 'b', 'c', 'd', 'e', 'f']
del alist[1:5]
print(alist)
(ch09_11)
As you might expect, del
handles negative indices and causes a runtime error if the index is out of range.
Nested Lists¶
- A nested list is a list that appears as an element in another list.
- To extract an element from the nested list, we can proceed in two steps.
- First, extract the nested list, then extract the item of interest.
- It is also possible to combine those steps using bracket operators that evaluate from left to right.
nested = ["hello", 2.0, 5, [10, 20]]
innerlist = nested[3]
print(innerlist)
item = innerlist[1]
print(item)
print(nested[3][1])
(chp09_nest)
Split and Join¶
The split
method breaks a string into a list of words.
By default, any number of whitespace characters is considered a word boundary.
song = "The rain in Spain..."
wds = song.split()
print(wds)
(ch09_split1)
An optional argument called a delimiter can be used to specify which
characters to use as word boundaries. The following example uses the string
ai
as the delimiter:
song = "The rain in Spain..."
wds = song.split('ai')
print(wds)
(ch09_split2)
Notice that the delimiter doesn’t appear in the result.
The inverse of the split
method is join
. You choose a
desired separator string, (often called the glue)
and join the list with the glue between each of the elements.
wds = ["red", "blue", "green"]
glue = ';'
s = glue.join(wds)
print(s)
print(wds)
print("***".join(wds))
print("".join(wds))
(ch09_join)
The list that you glue together (wds
in this example) is not modified. Also,
you can use empty glue or multi-character strings as glue.
list
Type Conversion Function¶
Python has a built-in type conversion function called
list
that tries to turn whatever you give it
into a list. For example, try the following:
xs = list("Crunchy Frog")
print(xs)
(ch09_list1)
Lists and for
loops¶
It is also possible to perform list traversal using iteration by item as well as iteration by index.
fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits: # by item
print(afruit)
(chp09_03a)
We can also use the indices to access the items in an iterative fashion.
fruits = ["apple", "orange", "banana", "cherry"]
for position in range(len(fruits)): # by index
print(fruits[position])
(chp09_03b)