Sbioer
Sbioer

Reputation: 235

How to convert a for loop output to a list?

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

Answers (4)

Eugene Soldatov
Eugene Soldatov

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

SirParselot
SirParselot

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

Avión
Avión

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

itzMEonTV
itzMEonTV

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

Related Questions