Extensions

List Slicing, Robust typecasting via Error Handling

Useful Tip: Tab completion in Spyder

When typing out the names of variables which you've declared above, you can press the tab key to autocomplete (or show a list of possible completions, from which you can then pick)

In practice, such tricks make writing large pieces of code much faster (tab completion also works with most syntax like print()) - especially if you're using informative, but long, variable names.

More List Stuff

List Slicing

Sometimes we want to access sub-sections of our list, without needing to manually get every item contained in that section. To this end we can use colons when accessing arrays.

  • This works like my_list[begin:end:step_size]

NOTE: you don't need to specify all three of these values - python will use default values:

  • begin = start of list

  • end = end of list

  • step_size = 1

sentence = ["What", "A", "Great", ",", "Guy","Never","Said", "Anything","Bad"]

# Emulate the media
out_of_context = sentence[4:8:1] # Get part of the list
print(out_of_context)

Min and Max

min() and max() do what you'd expect - So long as you have numbers in the list; string comparison is a bit less straightforward

Sort

Under the hood, min() and max() work by sorting the list first. We can do this manually by using .sort()In [24]:

Split

split() is a function which allows us to break up strings into sub-strings stored in a list

Join

join() is essentially the opposite of split, and allows us to nicely format our lists when we want to print them

Basic Error Handling

If we try to something which python can't, then we'll get an error. The jargon for this is that : "python throws an error", and we can "catch" these to stop our programs from crashing.

The syntax for is referred to as a "try, except":

Last updated

Was this helpful?