piddi
piddi

Reputation: 3

How to make the 2- dimensional list from the inputs given by user?

I want to take the multiple inputs from the user and store the data into the 2-D list.

But while doing this I am facing the problem which is the when I used to clear the list2 the data of the "Final List(list3)" also get cleared.

So, basically the desired output should look like this [[2,3,5],[7,8,9],[8,6,3]] after getting the 3 inputs from user.

But after the first input, list output looks like this [[2,3,5]] and at the very next entry the list gets all cleared and next output is [[7,8,9],[7,8,9]].

What changes do I need to make into the code?

list1 = []
list2 = []
list3 = []

while True:

    val1 = input("Input value1 ")
    list1.append(val1)
    val2 = input("Input value2 ")
    list1.append(val2)
    val3 = input("Input value ")
    list1.append(val3)
    for element in list1:
        list2.append(element)

    print(list2)
    list3.append(list2)
    print(list3)
    list1.clear()
    list2.clear()

    response = input(print("Do you want to continue ? (Y/N) :  "))
    if response.upper() == "Y":
        continue
    else:
        break

Output:

Input value1 2
Input value2 3
Input value 5
['2', '3', '5']
[['2', '3', '5']]
Do you want to continue ? (Y/N) : y
Input value1 7
Input value2 8
Input value 9
['7', '8', '9']
[['7', '8', '9'], ['7', '8', '9']]

Upvotes: 0

Views: 70

Answers (5)

Jonathan
Jonathan

Reputation: 286

Another way to tackle this is using a function to generate the sub list. This function is then called from the main loop that you developed. This not only allows the function to reuse the sub list generation code but also creates a local name space which can be used in each iteration of the function (i.e. each time it is called).

Also, please note that I have used the same variable name for the main list as well as the sub lists. Since functions create a local name space which is used with priority before the global names this is not a conflict:

list1 = []

# function to create sub lists which reuses the code and provides local name space
def newList():
    list1 = []
    val1 = input("Input value1 ")
    list1.append(val1)
    val2 = input("Input value2 ")
    list1.append(val2)
    val3 = input("Input value ")
    list1.append(val3)   
    return list1

# main loop calling the function newList() to get input for sub lists 
while True:
    list1.append(newList())
    print(list1)
    response = input(print("Do you want to continue ? (Y/N):"))
    if response.upper() == "Y":
        continue
    else:
        break

Upvotes: 0

losik123
losik123

Reputation: 590

Actually you overcomplicated the solution a bit in my opinion. Instead of using the global lists you're clearing in each iteration, why not use the list in the loop scope or dynamically create the list. That should do the trick as well and is far more readable:

resultList = []

while True:
    val1 = input("Input value1 ")
    val2 = input("Input value2 ")
    val3 = input("Input value3 ")
    resultList.append([val1, val2, val3])

    response = input(print("Do you want to continue ? (Y/N) :  "))
    if response.upper() == "Y":
        continue
    else:
        break

print(resultList)

Result:

Input value1 3                                                                                                                                  
Input value2 4                                                                                                                                  
Input value3 5                                                                                                                                  
Do you want to continue ? (Y/N) :                                                                                                               
Y                                                                                                                                           
Input value1 6                                                                                                                                  
Input value2 7                                                                                                                                  
Input value3 8                                                                                                                                  
Do you want to continue ? (Y/N) :                                                                                                               
N                                                                                                                                           
[['3', '4', '5'], ['6', '7', '8']]

Upvotes: 1

norok2
norok2

Reputation: 26886

I think the code is a bit messy, what you do need to do is to have a "inner" list that gets progressively populated, and once that is of the size you deem appropriate you just append (a copy of -- if you want to reuse the old "inner list") the whole inner list inside an "outer list".

One way of doing this (creating a new inner list at each iteation because it is more efficient than copying the old one and reusing the same object) wold be:

# we define upfront how many values we want in the inner list
NUM_INNER_VALUES = 3

# the outer list needs to be created outside the main loop
outer_list = []
# we set the control right in the `while`
response = 'Y'
while response.upper() == 'Y':
    # create a new `inner_list` and fill it in
    inner_list = []
    for i in range(NUM_INNER_VALUES):
        value = input(f"Input value {i + 1}: ")
        inner_list.append(value)
    outer_list.append(inner_list)
    # : optionally check the content of the outer list at each "row" iteration
    print('Outer list is currently: ')
    print(outer_list)
    response = input("Do you want to continue ? (Y/N) :  ")

The reason why you observe that the last input gets "repeated" is due to the fact that you define the lists outside of the loop and you keep reusing their memory.

This is similar to the following:

a = [1, 2, 3]
b = a

print(a)
# [1, 2, 3]
print(b)
# [1, 2, 3]

b[0] = -1
print(a)
# [-1, 2, 3]

as you can see, while we modified b, the values of a also changed because actually a and b are pointing to the same memory.

On the contrary, if you force the allocation of new memory for b, this does not happen:

a = [1, 2, 3]
b = a.copy()

print(a)
# [1, 2, 3]
print(b)
# [1, 2, 3]

b[0] = -1
print(a)
# [1, 2, 3]

EDIT

See @SamStafford's answer for a minimal change that would make your code work. Note that one of list1 or list2 is fundamentally useless.

Upvotes: 1

Igna
Igna

Reputation: 1127

In case you don't need to use lists I would recommend you use numpy arrays

concatenate does what you want, If you have two arrays and stack them to achieve your desired output

Usually, when you wanna work with numbers you should use arrays, I would use lists for text only.

Upvotes: 0

Samwise
Samwise

Reputation: 71454

You want to make a copy of list2 rather than just putting the original into list3.

list3.append(list2.copy())

Upvotes: 1

Related Questions