Arrays
The static arrays used in other languages like C
and C++
are not available in Python
.
Instead, you can use dynamic ones, known by the list
type:
>>> l = [1, 2, 3]
>>> len(l)
3
>>> for num in l:
... print(num)
...
1
2
3
>>> l.append(4) # [1, 2, 3, 4]
>>> l = [1, 2, "three"] # it can also contain mixed types
Operations
Let's check the complexity of the most common arrays' operations [1]:
Operation | Time Complexity | Space Complexity | Syntax |
---|---|---|---|
Size | len(l) | ||
Get i-th | l[i] | ||
Set i-th | l[i] = val | ||
Copy | [val for val in l] | ||
Append | l.append(val) | ||
Pop last | l.pop() | ||
Pop i-th | l.pop(i) | ||
Delete value | l.remove(val) | ||
Iterate | for val in l: print(val) | ||
Search | val in l | ||
Minimum | min(l) | ||
Maximum | max(l) |
Best Practices
Iterate over the list instead of using the index
# Good
for num in nums:
print(num)
# Not-so-good
for i in range(len(nums)):
print(nums[i])
Use enumerate
# Good
for i, num in enumerate(nums):
print(i, num)
# Not-so-good
for i in range(len(nums)):
print(i, nums[i])
Use enumerate
and start
argument
# Good
for i, num in enumerate(nums, start=1):
print(i, num)
# Not-so-good
for i, num in enumerate(nums):
print(i+1, num)
Use zip
to iterate over multiple lists
# Good
for num_a, num_b, num_c in zip(lst_a, lst_b, lst_c):
print(num_a, num_b, num_c)
# Not-so-good
assert len(lst_a) == len(lst_b) == len(lst_c)
for i in range(len(lst_a)):
print(lst_a[i], lst_b[i], lst_c[i])
Use reversed
for backward iteration
# Good
for num in reversed(nums):
print(num)
# Not-so-good
for i in range(len(nums) - 1, -1, -1):
print(nums[i])