Ch 7: Lists and Tuples
List Comprehension
A concise expression that creates a new list by iterating over the elements of an existing list. An expression that reads an input list, using the values of the input list to produce an output list. list1 = [1,2,3,4] list2 = [item for item in list1] The list comprehension begins with a result expression, followed by an iteration expression. The iteration expression works like a for loop. Each time it iterates, the target variable 'item' is assigned the value of an element. At the end of each iteration, the value of the result expression is appended to the new list.
Returning a List from a Function
A function can return a reference to a list. This gives you the ability to write a function that creates a list and adds elements to it, then returns a reference to the list so other parts of the program can work with it.
What is the difference between lists and tuples?
A list is mutable, which means that a program can change its contents. A tuple in immutable, which means that once its created, its contents cannot be changed.
Two-Dimensional Lists
A list that has other lists as its elements. A list of lists, also known as nested lists. Useful for working with multiple sets of data. It is common to think of a two-dimensional list as having rows and columns of elements. When processing the data in a two-dimensional list, you need two subscripts: one for the rows, and one for the columns. Programs that process two-dimensional lists typically do so with nested loops. The elements of a list can be virtually anything, including other lists. students = [['Joe', 'Kim'], ['Sam', 'Sue'], ['Laura', 'Chris']] print(students[0]) ['Joe', 'Kim']
List Slicing
A slicing expression selects a range of elements from a sequence. You have seen how indexing allows you to select a specific element in a sequence. Sometimes you want to select more than one element from a sequence. In Python, you can writes expressions that select subsections of a sequence, known as slices. A slice is a span of items taken from a sequence. When you take a slice from a list, you get a span of elements from within the list. To get a slice of a list, you write an expression in the following general format: list_name [ start : end ] 'start' is the index of the first element in the slice, and 'end' is the index marking the end of the slice. The expression returns a list containing a copy of the elements from 'start' up to (but not including) 'end'. Slicing elements can have step value, which can cause elements to be skipped on the list. You can also use negative numbers as indexes in slicing expression to reference positions relative to the end of the list. Invalid indexes do not cause Python to raise an exception: -if the end index specifies a position beyond the end of the list, Python will use the length of the list instead. -if the start index specifies a position before the beginning of the list, Python will use 0 instead. -If the start index is greater then the end index, the slicing expression will return an empty list.
Tuples
A tuple is an immutable sequence, which means that its contents cannot be changed. When you create a tuple, you enclose its elements in a set of parentheses. my_tuple = (1,2,3,4,5) Tuples support indexing. Tuples do not support: append, remove, insert, reverse, and sort If you want to create a tuple with just one element, you must write a trailing comma after the element's value. If you omit the comma, you will not create a tuple, you will only assign a value to a variable. my_tuple = (1, ) Tuples exist for performance. Processing a tuple is faster than processing a list. Tuples are safe because they are immutable. There are certain operations in Python that require a tuple.
Element
A value in a list or other sequence is referred to as an element.
The insert Method
Allows you to insert an item into a list at a specific position. You pass two arguments to the insert method: (1) an index specifying where the item should be inserted (2) the item that you want to insert
Iteration Expression
Also known as a loop, executes a statement known as the loop body repeatedly until the controlling expression is false (0).
Lists
An object that contains multiple data items. Each item is called an element. Dynamic data structures, meaning that items may be added to them or removed from them. You can use indexing, slicing, and various methods to work with lists in a program.
Indexing
Another way you can access the individual elements in a list. Each element in a list has an index that specifies its position in the list. Indexing starts at 0, so the first element is 0, the index of the second element is 1, and so forth. The index of the last element in a list is 1 less than the number of elements in the list. my_list = [10, 20, 30, 40] print(my_list [0] , my_list [1] , my_list [2] , my_list [3] ) The following loop also prints the elements of the list: index = 0 while index < 4: print(my_list [index]) index += 1 You can also use negative indexes to identify element positions relative tho the end of the list. The Python interpreter adds negative indexes to the length of the list to determine the element position. The index -1 identifies the last element in a list, -2 identifies the next to last element, and so forth. my_list = [10, 20, 30, 40] print(my_list [-1] , my_list [-2] , my_list [-3] , my_list [-4] ) 40 30 20 10
Totaling the Values on a List
Assuming a list contains numeric values, to calculate the total of those values, you use a loop with an accumulator variable. The loop steps through the list, adding the value of each element to the accumulator.
list ( ) function
Built into Python can convert certain types of objects to lists. numbers = list(range(5)) the list [0,1,2,3,4] is assigned to the numbers variable
The len Function
Built-in Python function Returns the length of a sequence, such as a list. my_list = [10, 20, 30, 40] size = len(my_list) The function returns the value 4, which is the number of elements in the list. This value is assigned to the size variable. The len function can be used to prevent an IndexError exception when iterating over a list with a loop: my_list = [10, 20, 30, 40] index = 0 while index < len (my_list): print(my_list [index]) index += 1
Result Expression
Can be used inside methods with a return value to refer to the result that the method will return upon completion.
The index Method
Earlier, you saw how the 'in' operator can be used to determine whether an item is in a list. Sometimes you need to know not only whether an item is in a list, but where it is located. The index method is useful in these cases. You pass an argument to the index method, and it returns the index of the first element in the list containing that item. If the item is not found on the list, the method raises a ValueError exception.
Processing Lists
How do programs process the data held in a list.
IndexError exception
Is raised if an invalid index is used. my_list = [10, 20, 30, 40] index = 0 while index < 5: print(my_list [index]) index += 1 The last time that this loop begins an iteration, the index variable will be assigned the value 4, which is an invalid index for the list. As a result, the statement that calls the print function will cause an IndexError exception to be raised.
List Methods and Useful Built-In Functions
Lists have numerous methods that allow you to work with the elements that they contain. Python also provides some built-in functions that are useful for working with lists. You can: -add elements -remove elements -change ordering of elements
The Repetition Operator
Makes multiple copies of a list and joins them all together. list * n 'list' is a list and 'n' is the number of copies to make numbers = [0] * 5 print(numbers) [0,0,0,0,0] numbers = [1,2,3]*3 print(numbers) [1,2,3,1,2,3,1,2,3]
Iterating over a List with the for Loop
One of the easiest ways to access the individual elements in a list is to use the for Loop. for variable in list: #list is the name of a list stmt stmt stmt etc. each time the loop iterates, variable will reference a copy of an element in list, beginning with the first element. The loop iterates over the elements in the list. numbers = [1,2,3,4] for num in numbers: print(num) 1 2 3 4 We cannot use the num variable to change the contents of an element in the list. If we change the value that num references in the loop, it has no effect on the list. numbers = [1,2,3,4] for num in numbers: num=99 print(num) 99
The max Function
Python built-in function. Accepts a sequence, such as a list, as an argument and returns the item that has the highest value in the sequence.
The min Function
Python built-in function. Accepts a sequence, such as a list, as an argument and returns the item that has the lowest value in the sequence.
The sort Method
Rearranges the elements of a list so they appear in ascending order (from the lowest value to the highest value)
The remove Method
Removes a specific item from the list, if that item is on the list. You pass an item to the method as an argument and the first element containing that item is removed. This reduces the size of the list by one element. All of the elements after the removed element are shifted one position toward the beginning of the list. A ValueError exception is raised if the item is not found in the list.
The del Statement
Some situations may require you to remove an element form a specific index, regardless of the item that is stored at that index. This can be accomplished with the del statement.
Working with Lists and Files
Some tasks may cause you to save the contents of a list to a file, so the data can be used at a later time. Likewise, some situations may require you to read the data from a file into a list. For example, suppose you have a file that contains a set of values that appear in random order, and you want to sort the values. One technique for sorting the values in the file would be to read them into a list. call the list's 'sort' method, then write the values in the list back to the file. Saving the contents of a list to a file is a straightforward procedure. Python file objects have a method named 'writelines' that writes an entire list to a file. A drawback to the writelines method is that it does not automatically write a newline ('\n') at the end of each item. Consequently, each item is written to one long line in the file. File objects in Python have a method named readlines that returns a file's contents as a list of strings. Each line in the file will be an item in the list. The items in the list will include their terminating newline character, which in many cases you will want to strip.
Using if Clauses with List Comprehensions
Sometimes you want to select only certain elements when processing a list. For example, suppose a list contains integers and you want to make a second list that contains only the integers from the first list that are less than 10. This can be accomplished with a loop. list1 = [1,12,2,20,3,15,4] list2=[item for item in list1 if item < 10] [result_expression iteration_expression if_clause] The result expression: 'item' The iteration expression: 'for item in list1' The if clause: if item < 10
Lists Are Mutable
The elements can be changed. An expression in the form list[index] can appear on the left side of an assignment operator. numbers = [1, 2, 3, 4, 5] print(numbers) numbers [0] = 99 print(numbers) 1, 2, 3, 4, 5 99, 2, 3, 4, 5
Averaging the Values in a List
The first step in calculating the average of the values in a list is to get the total of the values. The second step is to divide the total by the number of elements in the list.
Randomly Selecting List Elements
The random module provides a function named 'choice' that randomly selects an element in a list. You pass a list as an argument to the function, and the function returns the randomly selected element. To use the function, be sure to import the random module. The random module also provides a function named 'choices' that returns multiple randomly selected elements from a list. When you call the function, you pass a list and the argument k=n, where n is the number of elements you want the function to return. The function will then return a list of n randomly selected elements. The list that is returned form the choices function sometimes contains duplicate elements. If you want to randomly select unique elements, use the random module's 'sample' function instead.
Concatenating Lists
To concatenate means to join together. You can use the + operator to concatenate two lists. list3 = list1 + list2 You can also use the += augmented assignment operator to concatenate one list to another. list1 += list2 #this appends list2 to list 1. After this code executes, list 2 remains unchanged but list 1 has changed. list1 += [5, 6, 7] #this adds the numbers 5, 6, and 7 to the existing list You can only concatenate lists with other lists.
Copying Lists
To make a copy of a list you must copy the list's elements. Make a copy of the list so that the variables reference two separate but identical lists. One way to do this is with a loop that copies each element of the list.
Passing a List as an Argument to a Function
You can pass a list as an argument to a function. This gives you the ability to put many of the operations that you perform on a list in their own functions. When you need to call these function, you can pass the list as an argument.
Finding Items in Lists with the 'in' Operator
You can search for an item in a list using the in operator item in list 'item' is the item you are searching for. The expression returns true of item is found in the list, or false otherwise.
Converting Between Lists and Tuples
You can use the built-in list( ) function to convert a tuple to a list., and the built-in tuple( ) function to convert a list to a tuple. number_tuple = (1,2,3) number_list = list(number_tuple) print(number_list) [1,2,3]
Using a for Loop to Iterate by Index Over a List
You can use the len function along with the range function the get the indexes for a list. The expression range( len( names)) will give us the values 0, 1, 2, and 3. Because these values are the valid indexes for the list, we can use the expression in a for loop. names = ['Jenny', 'Kelly', 'Chloe', 'Aubrey'] for index in range( len (names)): print(names [index]) As the for loop iterates, the index variable will be assigned the values 0, 1, 2, and 3. The code will display the following: Jenny Kelly Chloe Aubrey
Sequence
an object that contains multiple items of data, stored one after the other. The items that are in a sequence are stored one after the other. Python provides various ways to perform operations on the items that are stored in a sequence
The append Method
commonly used to add items to a list The item that is passed as an argument is appended to the end of the list's existing elements
Statement that creates a list of integers
even_numbers = [2, 4, 6, 8] After this statement executes, the variable even_numbers will reference the list. The items that are enclosed in brackets and separated by commas are the list elements.
You can use the print function to display an entire list
even_numbers = [2, 4, 6, 8] print(even_numbers)
A list can hold items of different data types
info = ['Alicia', 27, 1550.87]
Two fundamental sequence types
lists and tuples
Plotting List Data with the matplotlib Package
matplotlib package is a library for creating two-dimensional charts and graphs
The reverse Method
reverses the order of the items in the list