Skip to content

Instantly share code, notes, and snippets.

@ethan-deng
Last active August 13, 2018 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethan-deng/b62d654a0d39eb8306a7c36baebf85fc to your computer and use it in GitHub Desktop.
Save ethan-deng/b62d654a0d39eb8306a7c36baebf85fc to your computer and use it in GitHub Desktop.

Python3

>>>
>>> squares[:]
[1, 4, 9, 16, 25]
  • You can also add new items at the end of the list, by using the append() method
  • multiple assignment
a, b = 0, 1
  • The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:
>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>>
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70
  • The function list() is another; it creates lists from iterables:
>>>
>>> list(range(5))
[0, 1, 2, 3, 4]
  • Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement

  • in keyword. This tests whether or not a sequence contains a certain value.

if ok in ('n', 'no', 'nop', 'nope'):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment