Dynamic array
Array is a collection of items of same data type stored at contiguous memory locations.
In Python, it's called list.
fruits = []
fruits = ['orange', 'apple', 'strawberry']
Add element
At the end
Use append(item). The item will be pushed back at the end of array.
fruits = ['orange', 'apple', 'strawberry']
fruits.append('lemon')
> fruits: ['orange', 'apple', 'strawberry', 'lemon']
At anywhere
Use insert(pos, item). The item will be inserted at position pos.
fruits = ['orange', 'apple', 'strawberry']
fruits.insert(2, 'pineapple')
> fruits: ['orange', 'apple', 'pineapple', 'strawberry']
Get array size
Use len(arr).
fruits = ['orange', 'apple', 'strawberry']
n = len(fruits)
> n: 3
Access element in array
Use bracket notation[index].
fruits = ['orange', 'apple', 'strawberry']
my_pick = fruits[1]
> my_pick: apple
index can be negative.
fruits = ['orange', 'apple', 'tangerine']
orange_variety = fruits[-1] # fruits[2]
> orange_variety: tangerine
Delete element
Use pop(index)
At the end
fruits = ['orange', 'apple', 'strawberry']
fruits.pop()
> fruits: ['orange', 'apple']
At anywhere
fruits = ['orange', 'apple', 'strawberry']
fruits.pop(1)
> fruits: ['orange', 'strawberry']
Delete all
fruits = ['orange', 'apple', 'strawberry']
fruits.clear()
> fruits: []
Extend array
Use list.extend(another_list) to concat another_list to the end of list.
zeros = [0, 0, 0]
zeros.extend(2*[0])
> zeros: [0, 0, 0, 0, 0]
Reduce array
Use slicing to get a part of the array, then assign it to itself.
nums = [0, 1, 2, 3, 4, 5]
nums = nums[0:2]
> nums: [0, 1]
When do arr[start:end], you can remember it as:
"get me that
arrfromstarttoendbutend"
Useful codes
Check if an array is empty
Check the len
arr = []
if len(arr) == 0:
print('Nothing is here!')
else:
print('Array is not empty!')
Iterate over a list
Use range(len_of_arr) to create range from 0 to len_of_arr - 1 with step = 1. Then loop through it.
arr = [4 ,8 , 2, 0, 0]
for i in range(len(arr)):
print(arr[i], end=' ')
> 4 8 2 0 0
Iterate over a list in reverse order
Use simple loop. Note that just like slicing array, range(start, end, step) is like "get me from start to end but not take that end".
arr = [4 ,8 , 2, 0, 0]
for i in range(len(arr) - 1, -1, -1):
print(arr[i], end=' ')
> 0 0 2 8 4
Or using reversed(array). The array will not be affected.
wordList = 'Python is great!'
for i in reversed(wordList) :
print(i, end='')
> !taerg si nohtyP
Oh wait, isn't wordList a string? Is it an array too?
Well, it is. Let's go to next module. 🚗