2

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
asked Mar 31, 2016 at 21:43
1
  • 1
    You may append only one object. If you want to append a list, create it and pass it as a argument - Temp.append([i, i+1]). Commented Mar 31, 2016 at 21:46

2 Answers 2

2

This will work: temp = [[i, i+1] for i in range(3)]

answered Mar 31, 2016 at 21:44
2
  • let me give a better example Commented Mar 31, 2016 at 21:46
  • @Adam: this is very good example. Take your time to learn some examples of list comprehension and you will soon find it really nice. Commented Mar 31, 2016 at 21:55
1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.