







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Lists are the simplest data structure in Python. A list is simply what it sounds like: a set of values in a particular order. Each value in a list is ...
Typology: Exams
1 / 13
This page cannot be seen from the preview
Don't miss anything!








Lists are the simplest data structure in Python. A list is simply what it sounds like: a set of values in a particular order. Each value in a list is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered lists of characters, except that the elements of a list can be any type. To create a list, you can use the bracket syntax: list_name = [item1, item2, item3, itemN] Here are three lists: In [1]: The len() function can be used on lists and returns the number of items in the list: In [2]: The elements of a list don't have to be the same type: In [4]: What's the last element of mixed_list?
Elements of a list are accessed using the bracket operator, the same way as the characters of a string. Just as with strings, the indexing of elements starts at 0, and the largest index is the length of the list - 1. In [5]: If an index has a negative value, it counts backward from the end of the list: Out[2]: 4 Out[5]: 'TGA' numbers = [ 1 , 2 , 3 , 4 ] # a list of integers sequences = ['ATG', 'TTT', 'GGG'] # a list of strings empty_list = [] # an empty list, analagous to an empty string len(numbers) mixed_list = ['ATG', 0 , 'TGA', 1.3, [ 1 , 2 , 3 ]] mixed_list[ 2 ]
In [6]:
Unlike strings, lists are mutable, meaning they can be changed. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be changed: In [7]: Traversing a list We can iterate through the elements of a list using a for loop, exactly the same way we iterated through the characters of a string: In [8]: However, if you want to change an element as you go along, you also need access to its index. Therefore we often use the following form of iteration through a list: In [10]: Out[6]: (^) 'TGA' Out[7]: [1, 5, 3, 4] 1 2 3 4 2 6 4 8 12 mixed_list[ - 3 ] t = [ 1 , 2 , 3 , 4 ] t[ 1 ] = 5 t t = [ 1 , 2 , 3 , 4 ] for e in t: print(e) t = [ 1 , 3 , 2 , 4 , 6 ] _# use a for loop combined with range() to
for i in range(len(t)): print(t[i] ***** 2 )
Write a function, list_square(my_list) , that prints the square of each value in my_list. In [21]: Slices List slices work exactly as they do for strings: In [23]: Lists as references to objects in memory In Python, variables are references to objects in memory. This is exemplified well with lists: In [28]: In [29]:
Out[23]: (^) [3, 4] Out[28]: False Out[29]: False def list_squares(my_list): #for i in range(len(my_list)): #print(my_list[i]**2) for i in my_list: print(i ****** 2 ) t = [ 1 , 2 , 3 ] list_squares(t) t = [ 1 , 2 , 3 , 4 , 5 , 6 ] t[ 2 : 4 ] a = [ 1 , 2 , 3 ] b = a #a == b #a is b b = a[:] #a == b a is b a = [ 1 , 2 , 3 ] b = [ 2 , 3 , 1 ] a == b
The equality operator for lists determines if all the elements of the two lists are the same, and in the same order. The is operator determines if two varaiables refer to the same object in memory. Since variables are just references to objects, if we assign one variable to another, both variables refer to the same object, and if we change one, that also changes the other: In [31]: If you want to modify a list and also keep a copy of the original, make a copy of the list, rather than a new reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy. The easiest way to clone a list is to use the slice operator: In [32]: Now you can make changes to b without worrying about affecting a. The enumerate() function adds a counter to an iterable, such as a value in a list: In [33]: This is useful if we want to iterate through a list keeping track of the position of each value. Let's write a function, double_values() , that doubles the values of items in a list, without worrying about changing the list: Out[31]: [1, 0, 3] Out[32]: (^) [1, 2, 3] 0, ATG 1, TGA 2, CCC a = [ 1 , 2 , 3 ] b = a b[ 1 ] = 0 a a = [ 1 , 2 , 3 ] b = a[:] b[ 1 ] = 0 a seqs = ['ATG', 'TGA', 'CCC'] for n, i in enumerate(seqs): # n is the counter, i is the element in the list print(f"{n}, {i}")
To append an item to a lisy, we can use the list.append(element) method: In [38]: Let's use append to write a function, powers_of_2(n) , that creates a list of powers of 2 for all integer numbers less than n : In [39]: To concatenate two lists, you can use the extend(list_of_elements) method: In [40]: You can also concatenate lists using the + operator: In [41]: Lists have other useful methods: list.count(value) : count the number of times a value occurs in a list list.index(value) : the index of the first occurrence of a value in a list list.insert(index, object) : insert an object at a specific position list.pop(obj = list[-1]) : remove a value at a given position, by default the last list.remove(object) : for removing a given object, regardless of its position list.sort() : sort a list numerically/alphabetically Out[38]: (^) [1, 2, 3, 4, 5] Out[39]: (^) [0, 1, 4, 9] Out[40]: [1, 2, 3, 4] Out[41]: [1, 2, 3, 4] t = [ 1 , 2 , 3 , 4 ] t.append( 5 ) t def powers_of_2(n): powers = [] for i in range(n): powers.append(i ****** 2 ) return powers powers_of_2( 4 ) a = [ 1 , 2 ] b = [ 3 , 4 ] a.extend(b) a a = [ 1 , 2 ] b = [ 3 , 4 ] a + b
Using the list below, briefly experiment with each of the above methods: In [47]: Lists and strings Strings can be thought of as a list of characters, and you can easily convert a string into a list using the list() function: In [50]: If you want to convert the string into a list of words, use a string's split method ( str.split(str=' ', num=string.count(str)) ): In [62]: Comma delimited files (.csv) are a common tabular data format. A line in a comma delimited file may look something like: Out[47]: (^) [1, 1, 2, 3, 4] Out[50]: ['A', 'T', 'A', 'G', 'A', 'G', 'A', 'G', ' ', 'A', 'T', 'G', ' ', 'C', 'G', 'A'] Out[62]: ['ATAGAGAG', 'ATG CGA'] t = [ 1 , 2 , 3 , 4 , 1 ] t.sort() t seq = 'ATAGAGAG ATG CGA' t = list(seq) t seq = 'ATAGAGAG ATG CGA' t = seq.split(' ', 1 ) t
In [73]: In [75]: We can also go in the opposite direction - from a list to a string using the join method: In [77]: Nested lists and matrices As we saw above, a nested list is a list that appears as an element in another list. To extract an element from a nested list, like the one below, we can take a two step approach: In [79]: Or in one step: In [81]: Nested lists are a way of representing a matrix. For example: In [ ]: Out[73]: (^) [1.23, 3.21, 6.45] Out[75]: [1.23, 3.21, 6.45] ATG,CCC,ATG Out[77]: ['ATG', 'CCC', 'ATG'] Out[79]: 8 Out[81]: 8 string_list = ['1.23','3.21','6.45'] t = list(map(float, string_list)) t # sneak peak: list comprehensions string_list = ['1.23','3.21','6.45'] t = [float(i) for i in string_list] t my_list = ['ATG', 'CCC', 'ATG'] #''.join(my_list) # join by empty string ','.join(my_list) # join by comma my_list # the actual list is unchanged nested_list = [ 1 , 2 , [ 7 , 8 , 9 ]] i = nested_list[ 2 ] i[ 1 ] nested_list = [ 1 , 2 , [ 7 , 8 , 9 ]] t = nested_list[ 2 ][ 1 ] t matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
The variable matrix is a list with three elements, where each element is a row of the matrix. We can select an entire row from the matrix or extract a single element from the matrix using the double-index form where the first index selects the row, and the second index selects the column: In [83]:
Extract the element in row 3, column 2 of the matrix below. In [84]: We can generate a matrix of zeros with user-defined numbers of rows and columns as follows: In [86]: Out[83]: (^) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Out[84]: 8 Out[86]: (^) [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix 1, 2, 3 4, 5, 6 7, 8, 9 ''' matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] matrix matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] i = matrix[ 2 ][ 1 ] i def zeros_matrix(rows, columns): """create a matrix with a given number of rows and columns """ matrix = [] for row in range(rows): matrix.append([ 0 ] ***** columns) return matrix zeros_matrix( 3 , 3 )
8g) Using list indices, extract the value in row 2, column 2 from the matrix in 8f. In [ ]: 8h) Using slicing, extract the first two rows from the matrix in 8f. In [ ]: 8i) Using an index, extract the last row of the matrix in 8f, assuming you don't know how many rows are in the matrix: In [ ]: 8j) Write a function, element_replace(matrix, n, i, c) , that replaces the element in the nth row and ith column with value c and returns a new matrix with the revision. In [ ]: 8k) Write a function called sum_rows(matrix) that sums the elements in each row in a matrix and returns the values as a list. Hint: use a nested for loop. The outer for loop will iterate through each row and the nested for loop will iterate through each element in each row. In [ ]: 8l) Write a function called sum_columns(matrix) that sums the elements in each column in a matrix and returns the values as a list. In [ ]: