Chapter 9 Lists
9.4 Lists and Loops¶
Item iteration. Similar to tuples, list objects are iterable, they can be iterated through by using a for loop.
The first for loop above prints a list of objects and their types, while the second for loop above prints the range of integers from 1 to 9, as indicated by the list.
Iteration through a sequence of numbers is frequently needed in programming, and Python provides a built-in function, range, which returns simple number sequences as list objects to facilitate number iteration. The range function can take one, two or three arguments. When a single argument n is given, the range function returns the list [0, 1, …, n − 1]. If n ≤ 0, an empty list is returned. When two arguments s and e are given, the range function returns the list [s, s + 1, s + 2,…, e − 1]. If s ≥ e, an empty list is returned. When three arguments, s, e and step are given, the range function returns the list [s, s + step, s + 2 ,…, e - 1].
The range function offers a new way to iterate through all the items in an iterable object. Different from using a for statement to iterate through an iterable object directly, the range function allows the use of a for statement to iterate through all the indices from 0 to the length of a sequence object.
Index iteration allows flexible orders of iteration. For example, the code below shows two ways to print the items of a list in the reverse order without modifying the list, both by index iteration.
The example below iterates through every second item in a list:
Index iteration also allows iterating through a half of a sequence object. For example, consider the palindrome number problem again. Index iteration allows the problem to be solved without converting the number into a list and making of copy of the list. The solution is based on the observation that if the ith digit on the left is the same as the ith digit on the right for all i, the corresponding number will be the same after the digits are reversed. Based on symmetry, as long as the left half of a list satisfies the condition above, the whole list satisfies the condition. The idea can be implemented as searching for a digit that is different from its counterpart. If such a digit is found, then the number is not a palindrome. Otherwise it is a palindrome.
Strings and Lists. Two of the most useful methods on strings involve lists of
strings. The split
method breaks a string into a list of words. By default, any number of whitespace characters is considered a word boundary.
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:
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.
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 comprehension. Let’s say we want to create a list from a sequence of values based on some selection criteria. An easy way to do this type of processing in Python is to use a list comprehension. List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
where the if clause is optional. For example,
The expression describes each element of the list that is being built. The for
clause iterates through each item in a sequence.
The items are filtered by the if
clause if there is one.
In the example above, the for
statement lets item
take on all the values in the list mylist
.
Each item is then squared before it is added to the list that is being built. The result is a list of squares of the values in mylist
.
Check your understanding
- [4, 2, 8, 6, 5]
- 5 is added to each item before the append is peformed.
- [4, 2, 8, 6, 5, 5]
- There are too many items in this list. Only 5 append operations are performed.
- [9, 7, 13, 11, 10]
- Yes, the for loop processes each item of the list. 5 is added before it is appended to blist.
- Error, you cannot concatenate inside an append.
- 5 is added to each item before the append is performed.
9.4Q-1: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = [ ]
for item in alist:
blist.append(item+5)
print(blist)
- Poe
- Three characters but not the right ones. namelist is the list of names.
- EdgarAllanPoe
- Too many characters in this case. There should be a single letter from each name.
- EAP
- Yes, split creates a list of the three names. The for loop iterates through the names and creates a string from the first characters.
- William Shakespeare
- That does not make any sense.
9.4Q-2: What is printed by the following statements?
myname = "Edgar Allan Poe"
namelist = myname.split()
init = ""
for aname in namelist:
init = init + aname[0]
print(init)
- [4,2,8,6,5]
- Items from alist are doubled before being placed in blist.
- [8,4,16,12,10]
- Not all the items in alist are to be included in blist. Look at the if clause.
- 10
- The result needs to be a list.
- [10].
- Yes, 5 is the only odd number in alist. It is doubled before being placed in blist.
9.4Q-3: What is printed by the following statements?
alist = [4,2,8,6,5]
blist = [num*2 for num in alist if num%2==1]
print(blist)
© Copyright 2024 GS Ng.