Skip to content

Instantly share code, notes, and snippets.

@zelark
Last active August 29, 2015 13:58
Show Gist options
  • Save zelark/9955245 to your computer and use it in GitHub Desktop.
Save zelark/9955245 to your computer and use it in GitHub Desktop.
>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> new_list = []
>>> for x in my_list:
... new_list.append(x * 2)
...
>>> new_list
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> new_list = [x * 2 for x in my_list]
>>> new_list
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> [str(x) for x in my_list]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> map(str, my_list)
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> new_list = []
>>> for x in my_list:
... if (x % 2) == 0:
... new_list.append(str(x))
...
>>> new_list
['2', '4', '6', '8', '10']
>>> new_list = [str(x) for x in my_list if (x % 2) == 0]
>>> new_list
['2', '4', '6', '8', '10']
>>> list_a = ['A', 'B']
>>> list_b = [1, 2]
>>> [(x, y) for x in list_a for y in list_b]
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]
>>> list_a = ['A', 'B']
>>> list_b = ['C', 'D']
>>> [[x+y for x in list_a] for y in list_b]
[['AC', 'BC'], ['AD', 'BD']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment