- Sep 2020
-
greenteapress.com greenteapress.com
-
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes itemsThe syntax for accessing the elements of a list is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
cheeses[0]
' Cheddar ' Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. numbers = [42, 123] numbers[1] = 5 numbers [42, 5] The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings: for cheese in cheeses: print(cheese) This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the built-in functions range and len : for i in range(len(numbers)): numbers[i] = numbers[i] 2 This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to
n
1, where n is the length of the list. Each time through the loop i gets the index of the next element. The assignment statement in the body uses i to read the old value of the element and to assign the new value. The + operator concatenates lists: a = [1, 2, 3] b = [4, 5, 6] c = a + b c [1, 2, 3, 4, 5, 6] The operator repeats a list a given number of times: [0] 4 [0, 0, 0, 0] [1, 2, 3] 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times. *ython provides methods that operate on lists. For example, append adds a new element to the end of a list: t = [ ' a ' , ' b ' , ' c ' ] t.append( ' d ' ) t [ ' a ' , ' b ' , ' c ' , ' d ' ] extend takes a list as an argument and appends all of the elements: t1 = [ ' a ' , ' b ' , ' c ' ] t2 = [ ' d ' , ' e ' ] t1.extend(t2) t1 [ ' a ' , ' b ' , ' c ' , ' d ' , ' e ' ] This example leaves t2 unmodified. sort arranges the elements of the list from low to high: t = [ ' d ' , ' c ' , ' e ' , ' b ' , ' a ' ] t.sort() t [ ' a ' , ' b ' , ' c ' , ' d ' , ' e ' ] Most list methods are void; they modify the list and return None . If you accidentally write t = t.sort() , you will be disappointed with the result.
-