I am currently having a problem, I'm wanting to add things to a list of list whilst creating the list of lists at the same time, for example here
Temp=[]
for j in range 10:
for i in range 3:
if j>1:
Temp.append(i, i+1)
but this is giving me an error.
the output that i am looking for would be in the examples case [[0, 1][1,2][2,3]]
Iron Fist
11k2 gold badges20 silver badges36 bronze badges
2 Answers 2
This will work: temp = [[i, i+1] for i in range(3)]
-
-
@Adam: this is very good example. Take your time to learn some examples of list comprehension and you will soon find it really nice.Jan Vlcinsky– Jan Vlcinsky03/31/2016 21:55:47Commented Mar 31, 2016 at 21:55
To fix your solution, just add [brackets] around the list:
Temp=[]
for i in range(3):
Temp.append([i, i+1])
If you don't mind tuples, consider this instead:
>>> zip(range(0,3), range(1,4))
[(0, 1), (1, 2), (2, 3)]
answered Mar 31, 2016 at 21:46
lang-py
Temp.append([i, i+1])
.