Boston Python Workshop 6/Loops

sorting lists
Use  to sort a list:

>>> names = ["Eliza", "Joe", "Henry", "Harriet", "Wanda", "Pat"] >>> names.sort >>> names ['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda']

Getting the maximum and minimum values from a list
>>> numbers = [0, 3, 10, -1] >>> max(numbers) 10 >>> min(numbers) -1

Generating a list of numbers easily with
The  function returns a list of numbers. This is handy for when you want to generate a list of numbers on the fly instead of creating the list yourself.

>>> range(5) [0, 1, 2, 3, 4]

Use  when you want to loop over a bunch of numbers in a list:

>>> numbers = range(5) >>> for number in numbers: ...    print number * number ... 0 1 4 9 16

We could rewrite the above example like this:

>>> for number in range(5): ...    print number * number ... 0 1 4 9 16