Skip to content

Instantly share code, notes, and snippets.

@giwa
Last active August 29, 2015 14:16
Show Gist options
  • Save giwa/b7dabc1dcd6c1bab2866 to your computer and use it in GitHub Desktop.
Save giwa/b7dabc1dcd6c1bab2866 to your computer and use it in GitHub Desktop.
Looping idioms in Python ref: http://qiita.com/giwa/items/d453017f8ac6db34a7db
>>> # Let's create lists
>>> colors = "red blue green yellow".split()
>>> colors
['red', 'blue', 'green', 'yellow']
>>> for i in [0, 1, 2, 3]:
print colors[i]
red
blue
green
yellow
>>> enumerate(colors)
<enumerate object at 0x106e55690>
>>> list(enumerate(colors))
[(0, 'red'), (1, 'blue'), (2, 'green'), (3, 'yellow')]
>>> for i, color in enumerate(colors):
print i, "-->", color
0 --> red
1 --> blue
2 --> green
3 --> yellow
>>> for color in sorted(colors):
print color
blue
green
red
yellow
>>> for color in sorted(colors, reverse=True):
print color
yellow
red
green
blue
>>> for color in sorted(colors, key=len):
print color
red
blue
green
yellow
>>> range(4)
[0, 1, 2, 3]
>>> for i in range(len(colors)):
print colors[i]
red
blue
green
yellow
>>> for i in colors:
print i
red
blue
green
yellow
>>> for i in [3, 2, 1, 0]:
print colors[i]
yellow
green
blue
red
>>> range(3, 0, -1)
[3, 2, 1]
>>> range(3, -1, -1)
[3, 2, 1, 0]
>>> range(len(colors) - 1, -1, -1)
[3, 2, 1, 0]
>>> for i in range(len(colors) - 1, -1, -1):
print colors[i]
yellow
green
blue
red
>>> for i in reversed(colors):
print i
yellow
green
blue
red
>>> for color in colors[::-1]:
print color
yellow
green
blue
red
>>> for i in range(len(colors)):
print i, "-->", colors[i]
0 --> red
1 --> blue
2 --> green
3 --> yellow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment