As a beginner to Python(SAGE) I want to put the output of this for loop into a list:

for y in [0,8] : for z in [0,1,2,3] : x=y+z print x 

The output is

0 1 2 3 8 9 10 11 

(vertically). I want a list so I can use it for a later operation: I want [1,2,3,8,9,10,11]. I found a similar question and I realize that the output is recalculated each time. Is there a simple way to store them in a list? Following a suggestion for the other answer, I tried "append" like this, but it gives an error message:

x=[] for y in [0,2*3] : for z in [0,1,2,3] : x=y+z x.append(x) print x 
4

7 Answers

You have a lots of ways! First, as a raw code, you can do this:

lst=[] for y in [0,8] : for z in [0,1,2,3] : x=y+z lst.append(x) print lst 

You can try list comprehension:

lst = [y+z for y in [0,8] for z in [0,1,2,3]] print lst 

You can also use itertool chain:

import itertools lst = list(itertools.chain(*[range(i, i+4) for i in [0,8]])) print lst 

Another way is itertool products:

import itertools lst = [y+z for y,z in list(itertools.product([0,8], [0,1,2,3]))] print lst 

In all cases, output is : [0, 1, 2, 3, 8, 9, 10, 11]

This should do the trick:

lst = [y+z for y in [0,8] for z in [0,1,2,3]] print(lst) # prints: [1,2,3,8,9,10,11] 

The reason your code did not work, is because your using the variable x for two different things. you first assign it to a list, then you assign it to a integer. So python thinks that x is a integer, and integers don't have the attribute append(). Thus Python raise an error. The remedy is just to name your variables different things. But you should use something more descriptive than x, y, and z, unless their 'throwaway' variables.

0

try this :

import itertools temp = [y+z for y,z in list(itertools.product([0,8], [0,1,2,3]))] 

You can also approach this functionally using itertools.product:

from itertools import product lst = [y + z for y, z in product([0, 8], [0, 1, 2, 3])] print(lst) 

will output [0, 1, 2, 3, 8, 9, 10, 11].

3

Try:

x = [y+z for y in [0,8] for z in [0,1,2,3]] 

You can simply use a list comprehension such as this one:

>>> lst = [y+z for y in [0,8] for z in [0,1,2,3]] >>> lst [0, 1, 2, 3, 8, 9, 10, 11] 

That's perfectly clear to any Python programmer.

Or you could use range:

>>> lst=[] >>> for l in (range(i, i+4) for i in [0, 8]): ... lst.extend(l) >>> lst [0, 1, 2, 3, 8, 9, 10, 11] 

Or, since some seem to like complicated answers:

>>> import itertools >>> lst = list(itertools.chain(*[range(i, i+4) for i in [0,8]])) >>> lst [0, 1, 2, 3, 8, 9, 10, 11] 

Because you set variable x from list to int at this line: x = y + z.

for-loops don't have scopes like a function or class, so if you set a variable out of the loop, the variable is the same as if it were in the loop.

5