Arrays (lists) Flashcards
What are arrays called in Python?
Lists
If I tried to append and pop from a Python list, would this throw an error?
No, Python lists are dynamic and can be used like stacks
How would you insert a value into a Python list?
arr.insert(1, 7)
This will insert the value 7 into the index 1
What is the time complexity of arr.insert()?
O(n) because if we insert a value into the first index of an array, we have to shift every other value which is the length of the list in the worst-case, thus O(n)
True or False: Python lists are considered arrays as well as stacks
True
What is the better alternative to using arr.insert()?
arr[0] = 0
In Python we can reassign elements in a list in constant time
If we wanted to initialize n to be equal to [1, 1, 1, 1, 1] - how would we do this in Python?
n = [1] * 5
How can we return the last element of a list in Python?
arr[-1]
How can we create a sublist from the following list?
arr = [1, 2, 3, 4, 5]
arr[1:3]
Result will be [2, 3]
How can we unpack a list in Python (assign variables to elements in the list)
a, b, c = [1 ,2 ,3]
Result will be a = 1, b = 2, c = 3
How would we loop through the elements in a Python list and get their values?
for i in range(len(nums)):
print(nums[i])
How would we loop through values only in a Python list?
for num in nums:
print(num)
How can we loop through a list and get both the index and the value in Python?
for i, num in enumerate(nums):
print(i, num)
How would we loop through multiple arrays simultaneously and unpack them?
Can use zip:
for n1, n2 in zip(nums1, nums2):
print(n1, n2)
How do we reverse the elements in a list without creating a new list?
nums.reverse()