Sad Sappy Sucker
Sad Sappy Sucker

Reputation: 1

Adding a list into another list in python

I am trying to make a loop that keeps adding list into another list.

list1 = [[1], [2], [3], [4]]
list2 = []

while True:
    list2.insert(len(list2), int(input("Here: ")))
    list1.insert(len(list1), list2)
    print(list1)
    list2.clear()

But then it gives me this:

Here: 10
[[1], [2], [3], [4], [10]]
Here: 20
[[1], [2], [3], [4], [20], [20]]
Here: 30
[[1], [2], [3], [4], [30], [30], [30]]
Here: 

But I want:

Here: 10
[[1], [2], [3], [4], [10]]
Here: 20
[[1], [2], [3], [4], [10], [20]]
Here: 30
[[1], [2], [3], [4], [10], [20], [30]]
Here: 

I am still at a basic level...

Upvotes: 0

Views: 50

Answers (2)

Dorian
Dorian

Reputation: 1488

list1.append([int(input("Here: "))])

If you use list.append(), it always adds to the end of the list which is generally what you do here in both cases.

The creation of a second list is unnecessary as the comments suggest. You can create a list of list directly by placing your input() into []-braces.

Upvotes: 0

wjandrea
wjandrea

Reputation: 32944

list1.insert(len(list1), list2) adds the same object to list1 inside the loop. You need to create a new object inside the loop instead. Just move the list2 = [] inside the loop

[copied from rdas's comment]

Upvotes: 2

Related Questions