15

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?

2
  • 1
    mylist = [(x+y) for x,y in zip(range(0,4,1),range(0,8,2))] Commented Oct 28, 2015 at 12:03
  • Do you specifically want the answers as strings? If you want to do further arithmetic (including sorting) then it's best to keep them as numbers (they also use less RAM in numeric form); you can easily convert them to strings when outputing them. Commented Oct 28, 2015 at 12:09

4 Answers 4

20

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Don't use class name list as variable name.
8

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']

Comments

3

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.

Comments

2

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'] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.