Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Sbioer Avatar asked Oct 28 '15 12:10

Sbioer


People also ask

How do you convert an output to a list in Python?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

Can you use a for loop for a list?

You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.

Can you convert a string to a list?

Strings can be converted to lists using list() .


2 Answers

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']
like image 89
Avión Avatar answered Sep 22 '22 17:09

Avión


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']
like image 36
itzMEonTV Avatar answered Sep 19 '22 17:09

itzMEonTV