Dark theme

Key Ideas


The key ideas for this part centre on making containers.


Key types

Tuples:
Assignment:
a = 2,3
a = (2,3)
a = tuple(some_other_container)

Subscription:
print(a[0])
The references to objects in tuples cannot change, though the contents of the objects can if mutable.

Lists:
Assignment:
a = [1,2,3]
a = list(some_other_container)
Subscription:
print(a[0])

Lists:
Assignment:
a = [1,2,3]
a = list(some_other_container)
a.extend(value_or_sequence)
a.insert(index_location, value_to_insert)
Subscription:
print(a[0])

Other:
a.clear()
a.remove(item_to_remove)
a.reverse()

Sets:
a = {"red", "green", "blue"}
a = set(some_other_container)
a.add("black")
Subscription(ish):
item_to_find in a
item_to_find not in a
a.issubset(b)
a.issuperset(b)
Other:
a.discard("blue")
a.clear()

Dict:
a = {1:"Person One", 2:"Person Two", 3:"Person 3"}
a = {"one"="Person One", "two"="Person Two"}

a[key] = value keys = (1,2,3)
values = ("Person One", "Person Two", "Person 3")
a = dict(zip(keys, values))
Subscription:
print(a[key])


General use of sequences

Packing (multiple returns pushed into one variable):
c = divmod (9,2)
Unpacking (one sequence into multiple variables):
a,b = (1,2)

sequence_length = len(sequence_name)

For sequences, you can index them thus:
a[0] # First
a[len(a) - 1] # Last
But also: a[-1] # Last
a[-len(a)] # First

2D sequences can be built thus:
a = [[1,2,3],[10,20,30],[100,200,300]]
And indexed thus:
print(a[0])
[1,2,3]
print(a[0][0])
0

2D collections can alternatively be created to transpose rows to columns thus:
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = zip(a,b)
d = list(c)
print(d)
[(1,10),(2,20),(3,30),(4,40),(5,50)]

Slices can be used to pull out multiple values:
a[i:j] # returns all the elements between i and j, including a[i] but not a[j]
a[i:j:k] # returns the same, but stepping k numbers each time.


range(start, stop, step) can be used to generate sequences:
range(0,-5,-1) # generates 0,-1,-2,-3,-4

min(a)
max(a)
a.index(x,i,j) # Index of the first occurrence of x in a (at or after optional index i and before index j).
a.count(b) Counts of b in a.
any(a) For a sequence of Booleans, checks whether any are true (or not zero for numbers)


Strings are immutable sequences of single-character strings, and can therefore be treated like tuples.
Useful string methods
a = str.split(string, delimiter)
a = some_string.split(delimiter)
str.find(strA, beg=0 end=len(string)) # Gives index position or -1 if not found
str.replace(substringA, substringB, int) # Replace all occurrences of A with B.
Useful escape characters:
\n # New line
\\ # Backslash