Data Structures List Quiz Flashcards
Python lists start from index 1
False, python lists are 0 indexed
Fill in the blank with the correct option:
lst = [1, 2, 3, 4]
for i in range(___):
answer: len(lst)
len(lst) -> returns 4
for i in range(len(lst)): -> will loop over 0 to 3
What will be the output from the following code:
lst = [1,2,3,4]
print(lst[4])ee
output: error: index out of range
runtime error
correct output: “IndexError: list index out of range”
Python list elements are stored in contiguous memory locations: True/False?
False: The objects of lists themselves are stored in random memory locations whereas the pointers (indexes) that make up the list are stored in sequential locations
What will be the output of the following piece of code?
def foo(value, lst): value = 1 lst[0] = 44
v = 3
lst = [1, 2, 3]
foo(v, lst)
print(v, lst[0])
print(v, lst[0]) -> 3, 44
What will the following code output?
list = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] def foo(m): v = m[0][0] for row in m: for element in row: if v < element: v = element return v
print(foo(list[0]))
print(foo(lst[0])) -> v = 4
What will be the output of the following code?
lst = [1, 2, 3, 4, 5, 6] for i in range(1, 6): lst[i - 1] = lst[i] # i = 1 -> lst[0] = 2 # i = 2 -> lst[1] = 3 # i = 3 -> lst[2] = 4 # i = 4 -> lst[3] = 5 # i = 5 -> lst[4] = 6 # [2, 3, 4, 5, 6, 6] < - this is the new list, lst for i in range(0, 6): print(lst[i]) # i = 0, print 2
output -> 2, 3, 4, 5, 6, 6
What is the output of the following code?
def f(i, values = []): values.append(i) print (values), return values f(1) f(2) f(3)
my original solution:
f(1) -> [1]
f(2) -> [2]
f(3) -> [3]
correct solution:
f(1) -> [1]
f(2) -> [1, 2]
f(3) -> [1, 2, 3]
action to remediate: understand scope of python functions and lists
What is the output of the following code?
lst = [[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]
for i in range(0, 4): # i = 0, lst[0] -> [1, 2, 3, 4], pop() -> 4 # i = 1, lst[1] -> [4, 5, 6, 7], .pop() -> 7 # i = 2, lst[2] -> [8, 9, 10, 11], .pop() -> 11 # i = 3, lst[3] -> [12, 13, 14, 15], .pop() -> 15 print(lst[i].pop()),
4, 7, 11, 15
Which of the following is/are difference(s) between Python lists and arrays?
Python lists use non-contiguous memory allocation
Python arrays use contiguous memory allocation
Python lists are not type specific