Module 9 - Lists and Tuples Flashcards

1
Q

What is a sequence? Name two types of sequences Python provides.

A

An object that contains multiple items of data
The generic term for an ordered set
Lists and tuples are two (of many) types of sequences

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s an object?

A

Anything that can contain information: a variable, a file, a string..

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s the difference between a list and tuple?

A

A list is mutable and tuple is immutable (not changeable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s a list? What’s an element?

A

A list is a sequence of values, an object that contains multiple data items
An element is an item in a list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What’s the format/ syntax for a list in Python?

A

list = [item1, item2, etc.]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

T or F: An error will occur if all items in a list are not the same type.

A

False - a list can hold different types of items

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you display a list? How do you convert certain objects to lists?

A

print function to display

list () function to convert to list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you make multiple copies of a list?

A

Repetition operator: makes multiple copies of a list and joins them together
list * n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the result of [1,2] * 4?

[2] + [4,7]?

A

[1,2,1,2,1,2,1,2]

[2,4,7]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you iterate over a list? What is the syntax?

A

you can use a for-loop!
for x in list:
(same way we did strings!)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What’s an index (w.r.t. lists)?

A

A number specifying the position of an element in a list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What’s the index of the first element? The nth element? The last element?

A

Index of first element is always 0, nth element has an index of n-1, last element is -1
(can use negative indexes to identify positions relate to the end of the list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What’s a good way to think about element vs. index numbering?

A

Think of index as location:
Count from 0!
The first element has a LOCATION (index) of 0
The nth element has a location of n-1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you find the length of a list? How do you find index from length?

A

can use len(list) function

index of the last element is len (list) - 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What happens if you iterate over a list w/ a loop and use an invalid index?

A

IndexError

To avoid this, be sure to use len( ) - 1 as the last index iteration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an exception?

A

AKA runtime error
The error does not appear until after the program has started running
(e.g., type code to iterate over a list, but the index is outside the boundary of the list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you assign a new value to an existing list element (e.g., the second element)?

A

list [1] = new_value

*must be valid index!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

T or F: Only lists of the same type can be concatenated.

A

False (Python 3)
(this was True in earlier versions of Python)
Can do: [1,2] + [‘a’,’e’]
Can also use +=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

If you assign: z=x+y, then you change x, what happens to z?

A

z remains old x+y (NOT the updated x value!)

*IMPORTANT!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is a slice?

A

A span of items that are taken from a sequence

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the list slicing format?

A

list[start : end]

Span is a list containing copies of elements from start up to, but not including, end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What happens if start or end not specified in a span/slice?

A

If start not specified, 0 is used for start index

If end not specified, len(list) is used for end index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Can slicing expressions include a step value or negative index?

A

Yes (negative indexes relative to end of list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

X = [1, 3, 5, 2, 9]
what do the following return?
X [-4:-2]
X [-1:2]

A

[3,5]

[ ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

X = [1, 3, 5, 2, 9]
what do the following return?
X [:1]
X [3:]

A

[1]
[2,9]

**REMEMBER first element is INDEX 0!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Which operator can you use to determine whether an item is contained in a list? Not contained?

A

‘in’ operator
‘not in’

general format: item in list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What kind of function is ‘in’?

A

Logical function

It returns True or False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the result of “[5,1] in [2,5,1,7]”? Why?

A

False
Because [5,1] as a list does not appear in the list [2,5,1,7]
Each element of the list [2,5,1,7] is its own entity and the ‘in’ operator searches for 5,1 as ONE entity (list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the result of ‘ac’ in ‘back’? Why?

A

True

strings do not follow the same rules as lists - ac is clearly in back

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How do you search if [5,1] is in [2,5,1,7]?

A

You will need a for loop to check each element of [5,1] whether they appear in the bigger list and in that order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Code used to add items to a list – item is appended to the end of the existing list

A

append(item)

if X = [1,3,5] and you wanted to add 4:
X.append(4)
[1,3,5,4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Code used to determine where an item is located in a list

A

index(item)
Returns the index of the first element in the list containing item
Raises ValueError exception if item not in the list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Code used to insert ‘item’ at position ‘index’ in the list

A

insert(index, item)

List expands in size, indices are shifted accordingly
No exception if you specify invalid index - if index beyond the end, item added to the end (if negative that’s beyond, added to beginning)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Code used to sort the elements of the list in ascending order (from lowest to highest value)

A

sort( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Code removes the first occurrence of ‘item’ in the list

A

remove(item)

ValueError exception if item not in list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Code that reverses the order of the elements in the list

A

reverse( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Code that removes an element from a specific index in a list

A

del statement

general format: del list[i]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What are the min and max functions? How do they work?

A

Built-in functions that returns the item that has the lowest or highest value in a sequence
The sequence is passed as an argument
max (sequence)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

All of the functions (except index, min, and max) will change the list. How do you retain a copy of the original list? (two ways - high level)

A

You must copy each element of the list

  • Create a new empty list and use a for loop to add a copy of each element from the original list to the new list
  • Create a new empty list and concatenate the old list to the new empty list
40
Q

Let’s say list1=[1,2,3] and you want to make a copy. Why can’t you do list1=list2 to copy?

A

If you change list1 then list2 will also change
That’s b/c list1 points to RAM location of [1,2,3]
So, when you assign list2 to list1, list2 now points to that same location
Now, when you CHANGE the [1,2,3] you will change BOTH list1 and list2
for example, if you do list1[0]=4, the RAM location now reads [4,2,3] which also means list2= [4,2,3]

41
Q

Make a copy of List1. Call it List2.

A

List2 = list(List1)
OR
List2 = List1[:]

42
Q

How do you calculate total of numeric values in a list? Average?

A

Use loop with accumulator variable

Divide total by len(list)

43
Q

T or F: List can be passed as an argument to a function

A

True

44
Q

How do you save the contents of a list to a file?

A

Use the file object’s writelines method

Does not automatically write \n at the end of each item (use a for loop to write each element and \n)

45
Q

How do you read data from a file?

A

Use the file object’s readlines method

46
Q

What is a two-dimensional list?

A

A list wherein each element is a list itself
AKA nested list
Common to think of it as rows and columns

47
Q

How do you process a two-dimensional list?

A

Need to use two indexes, typically use nested loops
list [row] [column]
for example, scores [2] [1]

48
Q

What is a tuple and what is its format?

A

An immutable sequence (once created, it cannot be changed)

Format: tuple_name = (item1, item2,…)

49
Q

Do tuples have the same operations as lists?

A

Yes - index, len, min, max, slicing, ‘in’, +, * operators

Do not support the ones that change the list: append, remove, insert, reverse, sort…

50
Q

What are the advantages of using tuples over lists?

A

Processing tuples is faster than processing lists
Tuples are safe
Some operations require tuples

51
Q

How do you convert a list to a tuple and vice versa?

A

list ( ) function to convert to list

tuple ( ) function to convert to tuple

52
Q

If you have a list called numbers, how would you double every element of the list?

A

for i in range(len(numbers)):
____numbers [i] = numbers [i] *2

len( ) returns the number of elements, n
range( ) returns a list, starting with 0 (default, because there’s only one argument), step 1 (default) and ending with n-1 (UP TO but not including n)
(this is perfect b/c n-1 is the LAST index)

53
Q

What happens with a ‘for loop’ over an empty list?
for x in [ ]:
___print(‘what happens?’)

A

It never runs the body

54
Q

T or F: If a list contains another list, the nested list counts as a single element.

A

True
[‘spam’, 1, [‘desk’, ‘fish’, ‘maybach music’], [1,2,3]]
each of the lists above counts as ONE element:
[‘desk’, ‘fish’, ‘mayback music’]
[1,2,3]

55
Q

What do the + and * operators do to lists?

Do they modify the current list or create a new list?

A

Concatenate and multiply:
[1,2,3]+[4,5,6] == [1,2,3,4,5,6]
[0]*4 == [0, 0, 0, 0]

Create a new list

56
Q

What happens when you omit both indices when slicing a list?
i.e., x[:]

A

It makes a copy of the entire list

*It’s often useful to make a copy before modifying lists

57
Q

T or F: You get an error message if a slice operator on the left side of an assignment tries to update multiple elements
t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
t [1:3] = [‘x’, ‘y’]

A

False - a slice operator on the left side of an assignment can update multiple elements:
[‘a’, ‘x’, ‘y’, ‘d’, ‘e’, ‘f’]

58
Q

Code that takes a list as an argument and appends all of the elements

A

extend (list that you want to add)

t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
['a', 'b', 'c', 'd', 'e']

(t2 is unmodified)

59
Q

t = [‘d’, ‘c’, ‘e’, ‘b’, ‘a’]

if you wrote, t = t.sort( )
what would be the result if you then printed t?

A

None

Most list methods are void; they modify the list and return None.

60
Q

Code to add up the elements in a list

A

sum ( )

t = [1, 2, 3]
sum (t)
6

61
Q

How would you use a loop to add up all the elements in a list?

A

t=[1,2,3]

total=0
for x in t:
___total+=x
print(total)

62
Q

What is a map?

A

A processing pattern that traverses a sequence and performs an operation on each element.

An operation that “maps” a function onto each of the elements in a sequence.

63
Q

What is a filter?

A

A processing pattern that traverses a list and selects the elements that satisfy some criterion.

64
Q

What is a reduce?

A

A processing pattern that traverses a sequence and accumulates the elements into a single result.

e.g., sum ( )

65
Q

Assume that a list of integers named salary_steps has been defined.

Write a statement that changes the value of the last element in the list to 160000.

Provide two different ways of doing this.

A

salary_steps [-1] = 160000

salary_steps [ len(salary_steps) - 1 ] = 160000

66
Q

Given a variable plist, that refers to a list with 34 elements, write an expression that refers to the last element of the list.

A

plist [-1]

plist [33]

67
Q

Given that L1 and L2 are both lists, write a statement that replaces the elements in L1 from index 5 through (and including) index 8 with all the elements of L2.

A

L1 [5:9] = L2

68
Q

Remove (item) vs. del statement - when do you use one over the other?

A

When you know the index, use del statement
When you know WHAT value (item) you want to delete, use remove (item) method

remove(item) removes the FIRST occurrence of ‘item’ in the list
del statement removes the element of the INDEX you specified

69
Q

What do you use to delete an element if you know the index AND you want to use that element?

A

pop (index)

t = ['a', 'b', 'c']
x = t.pop(1)

t now equals [‘a’, ‘c’]
and x is ‘b’

70
Q

What to use when you know the element you want to remove but not the index?

A

.remove(item)

71
Q

What do you use when you want to remove several elements?

A

del list [n:m]

72
Q

How do you convert from a string to a list? e.g., convert s = ‘spam’ to list.

A

list ( )
t = list (s)
t would be [’s’, ‘p’, ‘a’, ‘m’]

73
Q

How do you break a string into words? What’s the default delimiter and how do you change it?

A

split( )

s = ‘pining for the fjords’
t = s.split()
t becomes [‘pining’, ‘for’, ‘the’, ‘fjords’]

Default delimiter is space. To change, add an argument to split - for example,
s = ‘spam-spam-spam’
delimiter = “-“
s.split(delimiter) will give you [‘spam’, ‘spam’, ‘spam’]

74
Q

What is the inverse of split? How do you use it?

A

join - takes a list of strings and concatenates the elements

It is a string method, so you have to pass the list as a parameter:
t = ['pining', 'for', 'the', 'fjords']
delimiter = ' '
s = delimiter.join (t)
s becomes 'pining for the fjords'
75
Q
a = 'banana'
b = 'banana'

Are these referring to the SAME string or TWO strings with the same values?

A

use the ‘is’ operator to check!

It's the SAME string: 
a = 'banana'
b = 'banana'
a is b
True
76
Q
a = [1, 2, 3]
b = [1, 2, 3]

Are these referring to the SAME list or TWO lists with the same values?

A

TWO objects! (two lists)

a is b will return False

The two lists are EQUIVALENT but not IDENTICAL

77
Q

T or F: if two objects are equivalent, they are also identical.

A

False.

If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

78
Q

Value vs. Object: If you evaluate [1, 2, 3], what do you get?
What happens if another list has the same elements?

A

A list OBJECT whose VALUE is a sequence of integers

If another list has the same elements, we say it has the same value, but it is not the same object

79
Q

What is a reference?

A

The association of a variable with an object

If ‘a’ refers to an object and you assign b = a, then both variables refer to the same object.

80
Q

What do you call it when an object with more than one reference has more than one name?
What is we change the object?

A

We say that object is aliased
If the aliased object is mutable, changes made with one alias affect the other

*AVOID aliasing!
Immutable objects like strings - it’s OK to alias: e.g.,
a = ‘banana’
b = ‘banana’

81
Q

List vs. string methods: which one modifies the argument vs. creates a new object?

A

Most list methods modify the argument and return None.
This is the opposite of the string methods, which return a new string and leave the original alone.
Remember, strings are immutable!

82
Q

The list method t.append(‘x’) returns what?

Assume t=[‘y’, ‘p’] and ‘x’ is the element to add.

A

None.

Most list methods are VOID - i.e., they modify the list and return None.

83
Q

What happens when you pass a list to a function?

A

The function gets a reference to the list. If the function modifies the list, the caller sees the change.

84
Q

What is the result of the following?
x = ‘letters’
del x[0]

A

Error: str’ object doesn’t support item deletion

85
Q

What are some list operations that create NEW lists (instead of modifying existing lists)?
Why is this important?

A

+ concatenate, * repitition, [1: ] slicing

The original list is unmodified! Be mindful that the operation will return the new list
(if it modifies, it returns ‘None’)

86
Q

How do you represent a tuple syntactically? (two ways)

A

Comma-separated list of values (can also enclose in parentheses)
t = ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)

87
Q

How do you create a single-element tuple? (two ways)

A

MUST include a final comma:
t1 = ‘a’,

Or convert to tuple:
t = tuple( )

A value in parentheses is NOT a tuple!!
t1 = (‘a’) is a STRING

88
Q

What happens when you convert a string to a list or tuple?
t = ‘bad’
What is list (t) and tuple (t) ?

A

list (t) = [‘b’, ‘a’, ‘d’]

tuple (t) = (‘b’, ‘a’, ‘d’)

89
Q

You can’t modify the elements in a tuple, but you can replace one tuple with another. How?

A
t = ('a', 'b', 'c', 'd', 'e')
t = ('A',) + t [1: ]

This statement makes a new tuple and then makes t refer to it.

90
Q

How do the relational operators work with sequences?

A

Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered

91
Q

The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder.
How would you store the elements separately?
e.g., divmod (7, 3)

A
divmod (7, 3) would return 2, 1 (quotient and remainder) 
to store separately, 
quot, rem = divmod (7, 3) 
this would result in 
quot = 2 
rem = 1
92
Q

What object type would this return? why?

def min_max(t):
\_\_\_\_return min(t), max(t)

How do you change the object type?

A

tuple because the return value is separated by commas

to return as a list, can either add list function:
‘return list ((min (t), max(t))’
**BE SURE to do double parentheses! List function only takes ONE argument!

OR can add brackets: ‘return [min (t), max (t)]’

93
Q

What can you do to fit the number of arguments you have INTO the number of arguments a function takes?

A

can use the * operator

A parameter name that begins with * gathers (or scatters) arguments into a tuple

94
Q

Sum ( ) only takes two arguments

Write a function called sum_all that takes any number of arguments and returns their sum

A
def sum_all (*s): 
\_\_\_x=sum (s) 
\_\_\_return x

*s GATHERS (or scatters, if it’s a variable) the arguments into a tuple

95
Q

How do you choose between sequences: string, list or tuple?

A

Things to consider:

  1. want immutable? (then pick string or tuple)
  2. element composition (string is char only)
  3. sometimes, it is syntactically simpler to create a tuple than a list (like in return statements)
  4. if you are passing a sequence as an argument to a function, using tuples reduces potential of unexpected aliasing
96
Q

What function can you use if you want to sort a tuple or string?

A

sorted ( )

takes any sequence and returns a NEW list with the same elements in sorted order

97
Q

What is ‘zip’?

A

Built-in function that returns a zip object
You can then use this object in a ‘for loop’ to interleave two sets of sequences

s = 'abc'
t = [0, 1, 2]
for pair in zip(s, t):
\_\_\_print (pair) 
('a',0)...