Nibaga
Nibaga

Reputation: 25

I can't display the list correctly

list2 = []
q = int(input("Quantos contatos deseja adicionar? "))
for i in range(q):
    list1 = []
    nome = list1.append(input("Nome: "))
    num = list1.append(input("Número: "))
    list2.append(list1)

print(list1)
print(list2)

For example I want list1 to be

['abc', '123', 'def', '456', 'ghi', '789']

and list 2

[['abc', '123'], ['def', '456'], ['ghi', '789']]

However it prints

['ghi', '789']

[['abc', '123'], ['def', '456'], ['ghi', '789']]

And if I put outside the range it prints

['abc', '123', 'def', '456', 'ghi', '789']

[['abc', '123', 'def', '456', 'ghi', '789'], ['abc', '123', 'def', '456', 'ghi', '789'], ['abc', '123', 'def', '456', 'ghi', '789']]

Why is it overwriting the first 2 elements?

Upvotes: 1

Views: 57

Answers (3)

netdsg
netdsg

Reputation: 1

I think it's because list1 is inside the loop and gets set to null with each iteration.

I tried this and it produced the result you were looking for:

list2 = []

q = int(input('How many contacts would you like to add?: '))
list1 = []
    for i in range(q):
    tempList= []
    name = input('Name: ')
    number = input('Number: ')
    tempList.append(name)
    tempList.append(number)
    list1.append(name)
    list1.append(number)
    list2.append(tempList)

print(list1)
print(list2)

Output:

['abc', '123', 'def', '456', 'ghi', '789']

[['abc', '123'], ['def', '456'], ['ghi', '789']]

Upvotes: 0

Krupal Tharwala
Krupal Tharwala

Reputation: 1116

It gets overwritten because each time list1 gets reset in each iteration. Try this one :

list2 = []
q = int(input("Quantos contatos deseja adicionar? "))
list1 = []
for i in range(q):
    list3 = []
    nome = list1.append(input("Nome: "))
    num = list1.append(input("Número: "))
    list3 = list1[(i*2):]
    list2.append(list3)

print(list1)
print(list2)

This gives expected output that you mentioned.

Upvotes: 0

AER
AER

Reputation: 1531

Answer: It is overwriting the first 2 elements because you are resetting it each time in the for loop by executing list1 = [].

How-to: This is a necessity given that list1 is an input and if you want to append it to list2 it has to be the new one. I'd suggest creating a new variable as it is logically incompatible to try to get list1 to do both. I'm using list_entry below to achieve what you want to append to list2. list1 will print as you wish.

list1 = []
list2 = []
q = int(input("Quantos contatos deseja adicionar? "))
for i in range(q):
    nome = input("Nome: ")
    num = input("Número: ")
    list1.append(nome)
    list1.append(num)
    list2.append([nome, num])

print(list1)
print(list2)

On a further note nome and num were returning empty as the append function is reflexive and operates on the object it's attached to without returning anything.

Upvotes: 1

Related Questions