Python Hints

Indexing in Python

>>> lst = [3, 1, 5, 2, 4]
>>> lst[0]   # get first element
3
>>> lst[-1]  # get last element
4
>>> lst[-2]  # get second to last element
2
>>> lst[0:3] # get first 3 elements
[3, 1, 5]
>>> lst[:3]  # get first 3 elements
[3, 1, 5]
>>> lst[1:]  # get 2nd element on
[1, 5, 2, 4]
>>> lst[1:4] # get 2nd through 4th element
[1, 5, 2]

Emptying a list in Python

Since Python 3.2+, you can empty a list like this:

>>> lst = [1, 2, 3]
>>> lst.clear() # returns None
>>> print(lst)
[]

This will not work:

a = [1, 2, 3, 4]
for item in a:
    a.remove(item)

Imagine your list is [1, 2, 3, 4]. First, the one is removed so the 2 becomes the first number in the list. Then Python moves to the second element in a which is 3, not 2. So the 2 is skipped, as is the 4.

for loop tricks in Python

There are two useful constructs in Python for loops: continue and break.

Whenever Python sees the continue keyword, it will move on to the next iteration of the loop:

for x in [1, 2, 3, 4, 5]:
    if x == 3 or x == 4:
        continue
    
    print(x)
1
2
5

Whenever Python sees the break keyword, it will completely stop the loop:

for x in [1, 2, 3, 4, 5]:
    if x > 3:
        break

    print(x)
1
2
3

Hashtable/Dictionary Tricks in Python

Working with dictionary keys/values:

Note: These methods get rid of the efficiency of a hashtable, so in general only use them if you have to iterate over all keys/values in a hashtable.

>>> a = {'hi': 3, 'bye': 4}

>>> # this is the most "Pythonic" way to loop
>>> # over a hashtable
>>> for key in a:
...    print(key, a[key])
hi 3
bye 4

>>> list(a.keys())
['hi', 'bye']

>>> list(a.values())
[3, 4]

>>> list(a.items())
[('hi', 3), ('bye', 4)] # the elements are "tuples": see below

>>> for key, val in a.items():
...     print(key, value)
hi 3
bye 4

Tuples: https://www.w3schools.com/python/python_tuples.asp

Removing keys:

>>> a = {'hi': 3, 'bye': 4}
# pop both removes the 'hi' key and returns
# the value 3 (associated with the 'hi' key)
>>> a.pop('hi') 
3
>>> print(a)
{'bye': 4}