Lists
Common Operations
item | action |
---|---|
my_list = [1, 2, 3] |
declares a list |
my_list = [] |
declares an empty list |
my_list[2] = 4 |
modifies an element in the list |
my_list.append(8) |
adds 8 to the end of the list |
my_list.insert(0, 1) |
inserts 1 before index position 0 |
del my_list(0) |
removes the item at index 0 |
x = my_list.pop() |
pops the item from the end of the list and assigns it to x |
x = my_list.pop(1) |
pops the item from index position 1 and assigns it to x |
my_list.remove('b') |
removes the first occurrence of 'b' from the list |
my_list.sort() |
in place sort of the list |
my_list.sort(reverse=True) |
in place sort of the list in reverse order |
sorted(my_list) |
returns a copy of the list in sorted order (doesn't change order of the original list) |
sorted(my_list, reverse = True) |
as above but returns a list in reverse order |
my_list.reverse() |
in place reverse of the current ordering of the list. (NB. does not sort) |
len(my_list) |
returns the number of items in that list |
min(my_list) |
returns the smallest value in the list |
max(my_list) |
returns the largest value in the list |
sum(my_list) |
returns the sum of all the values in the list (assuming valid types in list) |
Looping
for item in my_list:
print(item)
List Comprehension
powers_of_two = [2**value for value in range(0,11)]
Copying
listb = lista # NOPE! This is just copying a reference to the list
listb = lista[:] # copies the contents of lista to listb
Tuples
Defined with round brackets. Basically an immutable list (cannot add, update or remove items in a tuple)
Tuples can be reassigned
my_tuple = (1, 2, 3, 4)
my_tuple = (3, 2, 1)