Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put Python loop output in a list

Tags:

python

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
like image 532
Albert Avatar asked Sep 05 '16 00:09

Albert


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

like image 153
jbsu32 Avatar answered Sep 27 '22 19:09

jbsu32


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.

like image 33
Christian Dean Avatar answered Sep 27 '22 21:09

Christian Dean