0

Again with a problem, this time it's about lists. I already know that I can put lists into lists but if I do that, all mini lists are just the last list I put in. Here is my program:

g = int(input ('How many lists?'))
while g > 0 :
    Zwi.clear()
    print('')
    print('')
    print('')      
    co = float(input ('object 1'))
    Zwi.append(co)
    co = float(input ('object 2'))
    Zwi.append(co)
    co = float(input ('object 3'))
    Zwi.append(co)
    co = float(input ('object 4'))
    Zwi.append(co)
    Coords.append(Zwi)
    g = g - 1
print(Coords)

For example, if I put in 4 Lists and then

1,2,3,4

2,4,3,1

7,4,2,5

9,8,7,6

it only puts out

9,8,7,6,9,8,7,6,9,8,7,6,9,8,7,6

So thanks in advance, bye.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Banana
  • 21
  • 1
  • 4
  • 1
    `Zwi` is always _the same list_. You have to create a _new list_ every iteration. – Aran-Fey Nov 11 '17 at 09:54
  • since list works on references so if you clear the pointed list it will effect the main list that has element pointing to another list – Nimish Bansal Nov 11 '17 at 09:55
  • Could be that your appending a reference to Zwi. So, it'll be in whatever state Zwi ends at. A quick way to check is to update the Zwi list after processing, then printing Coords to see if it changes the result. – Gry- Nov 11 '17 at 09:56
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Aran-Fey Nov 11 '17 at 10:01
  • See the linked question for an explanation of what's happening in your code. It's basically the same problem as yours, except you're never even trying to copy your list (or create a new one). – Aran-Fey Nov 11 '17 at 10:02
  • seems to be working fine here: https://repl.it/OHZy/0 – Alex Efimov Nov 11 '17 at 10:05
  • @AlexEfimov Not sure how you came to that conclusion. If you enter more than 1 list, they'll all be the same. – Aran-Fey Nov 11 '17 at 11:04

2 Answers2

0

Don't clear your list:

Zwi.clear()

Make a new one each time:

Zwi = []

The former uses the same list for each collection of inputs and hence adds the same list four times. The latter creates four new lists. That is what you want.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
0

This works for me:

g = int(input ('How many lists?'))
Coords = []
while g > 0 :
    Zwi = []
    print('')
    print('')
    print('')      
    co = float(input ('object 1'))
    Zwi.append(co)
    co = float(input ('object 2'))
    Zwi.append(co)
    co = float(input ('object 3'))
    Zwi.append(co)
    co = float(input ('object 4'))
    Zwi.append(co)
    Coords.append(Zwi)
    g = g - 1
print(Coords)
T C Molenaar
  • 3,205
  • 1
  • 10
  • 26