Reputation: 235
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?
Upvotes: 15
Views: 64820
Reputation: 10135
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.
Upvotes: 3
Reputation: 2700
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']
Upvotes: 2
Reputation: 8386
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']
Upvotes: 20
Reputation: 20339
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']
Upvotes: 8