Jed Rembold & Fred Agbo
March 6, 2024
Given the code to the right, what would be the final printed value of
A
?
['Fox', 'Giraffe', 'Hippo', 'Iguana']
['Fox', 'Hippo', 'Iguana']
['Iguana', 'Fox']
['Fox', 'Iguana']
A = [
'Fox',
'Giraffe',
'Hippo'
]
A.append('Iguana')
A[:].reverse()
B = A
for anim in B:
if anim[1] == 'i':
B.remove(anim)
print(A)
Commonly will make lists with a simple:
even_digits = [ 2, 4, 6, 8 ]
But in many cases, it is easier to specify the elements of a list
using a sequence of values generated by a
for
loop. For instance
even_digits = [ ]
for i in range(0, 10, 2):
even_digits.append(i)
Python gives us a shorthand notation to achieve this:
even_digits = [ i for i in range(0, 10, 2) ]
The simplest list comprehension syntax is:
[ expression iterator ]
where expression
is any Python expression
and iterator
is a
for
loop header
The iterator component can be followed by any number of additional modifiers
for
loop headers for nested
loopsif
statements to select specific
valuesExample: all even numbers to 20 not also visible by 3
[i for i in range(0,20,2) if i % 3 != 0]
list1 = [2,4,6,5,3]
list2 =[]
for i in range(len(list1)):
if list1[i]%2==0: ## eliminating all odd elements
list2.append(list1[i])
print(list2)
list1 = [2,4,6,5,3]
list2 = [list1[i] for i in range(len(list1)) if list1[i]%2==0]
print(list2)
Method | Description |
---|---|
str.split() |
Splits a string into a list of its components using whitespace as a separator |
str.split(sep) |
Splits a string into a list using the specified separator
sep |
str.splitlines() |
Splits a string into list of strings at the newline character |
str.join(list) |
Joins the elements of the list into a
string, using str as the separator |
We know that elements of a list can be lists in and of themselves. If the lengths of all the lists making up the elements of a list remain fixed, then the list of lists is called a multidimensional array
In Python, we can create multidimensional arrays just by creating lists of constant length as the elements to another list
magic = [ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]
We can always get the individual element of one of the inner lists by using 2 indices.
magic[1][1] = 5
magic[-1][0] = 6
[ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]