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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With