Arrays are called lists in python
arr = [1, 2, 3]
print(arr)Arrays in python can be used as a stack
arr.append(4)
arr.pop()However, we can also insert values in the middle since its not actually a stack, however this is O(n) operation
arr.insert(1, 7) # inserts 7 at index 1Indexing an array is stil O(1), so is changing the value at the index
arr[0] = 0Initialising arrays
To initialise an array of size n with default value of 1
n = 5
arr = [1] * n # [1, 1, 1, 1, 1]Indexing arrays
arr[-1] is actually not out of bounds but the last value
arr = [1, 2, 3]
print(arr[-1]) # 3To read the second last value ⇒ arr[-2]
Array slicing
To get a sublist of an array (last index is non-inclusive)
arr = [1, 2, 3, 4, 5]
print(arr[1:3]) # [2, 3]Unpacking
Taking out all the contents of the array and assigning them
a, b, c = [1, 2, 3]But we must make sure that the number of variables on the LHS is equal to the number of variables in the array
Looping through arrays
nums = [1, 2, 3]
# Using index
for i in range(len(nums)):
print(nums[i])
# Without index
for n in nums:
print(n)
# With index and value
for i, n in enumerate(nums):
print(i, n)Zip
If we want to loop through multiple arrays simultaneously
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
for n1, n2 in zip(nums1, nums2):
print(n1, n2)Reversing an array
nums = [1, 2, 3]
nums.reverse()Sorting
arr.sort()
arr.sort(reverse=True)Sorting a list of strings using the default sort will sort it in alphabetical order
arr.sort() #alphabetical
arr.sort(key=lambda x: len(x)) # Custom sort by the length of the stringList comprehension
arr = [i for i in range(5)] # [0, 1, 2, 3, 4]
arr = [i+i for i in range(5)] # [0, 2, 4, 6, 8]2D lists
arr = [[0] * 4 for i in range(4)]However, the not so right way to create a 2D list:
arr = [[0] * 4] * 4This is because each of the 4 rows will be the same and modifying one row will modify all of the rows. We are not creating 4 unique rows.