For example:
for y,x in zip(range(0,4,1),range(0,8,2)):
print(x+y)
Returns:
0
3
6
9
What I want is:
['0', '3', '6', '9']
How can I achieve this?
The easiest way for your understanding, without using list comprehension, is:
mylist = []
for y,x in zip(range(0,4,1),range(0,8,2)):
mylist.append(str(x+y))
print mylist
Output:
['0','3','6','9']
list as variable name.Try this using list comprehension
>>>[x+y for y,x in zip(range(0,4,1),range(0,8,2))]
[0, 3, 6, 9]
>>>[str(x+y) for y,x in zip(range(0,4,1),range(0,8,2))]
['0', '3', '6', '9']
You can generate list dynamically:
print [str(x+y) for x, y in zip(range(0,4,1), range(0,8,2))]
['0','3','6','9']
This technique called list comprehensions.
You could skip the for loops and use map() and import add from operator
from operator import add
l = map(add,range(0,4,1),range(0,8,2))
print l
[0, 3, 6, 9]
And if you want it as strings you could do
from operator import add
l = map(add,range(0,4,1),range(0,8,2))
print map(str, l)
['0','3', '6', '9']
mylist = [(x+y) for x,y in zip(range(0,4,1),range(0,8,2))]