dubey
dubey

Reputation: 41

creating nested lists in python using for loop

My requirements: [[R,88],[A,85],[S,78]]

My code:

n =int(input())
lst = []
for i in range(n):
    print("Enter Name " + str(i+1))
    lst.append([input()])
    for j in range(i,i+1):
        print("Enter Score " + str(j+1))
        lst.append([float(input())])
    
print(lst)

My results: [[R],[88],[A],[85],[S],[78]]

I would like to do it using for loops preferably, i know there might be easier ways to do it using list comprehensions and stuff but the fact of the matter is that I'm new to coding and I'm yet to cover those topics. Would appreciate if someone could show me how to do it using for loops.

I'm new to the space so apologies in advance if I'm not following the standard practices or playing by the rules :p

Upvotes: 0

Views: 4165

Answers (2)

Udipta kumar Dass
Udipta kumar Dass

Reputation: 151

The case you have asked can be simply implemented using single loop without nesting loops, Please find below code,

Note : Nested code will be required in case you will need multiple (> 2) list elements in the inner list. Let me know in comment if you need multiple elements so taht i can help with the nested loop situation

n =int(input("Enter the number of entries : "))
outer_list = []
for i in range(n):
    name = input("Enter Name " + str(i+1) + " : ")
    score = input("Enter Score " + str(i+1) + " : ")
    inner_list = [name, int(score)] # Change int to float if required
    outer_list.append(inner_list)
    
print(outer_list)

Output:

[['R', 88], ['A', 85], ['S', 78]]

Upvotes: 2

Shivam Roy
Shivam Roy

Reputation: 2061

You need to create a list inside the loop and append both the values to it, and ultimately append them to the bigger list. Also, you're appending each element as a list value, you should remove the square braces as well while taking the input, likewise:

n =int(input())
lst = []
for i in range(n):
    sub_lst = []
    print("Enter Name " + str(i+1))
    sub_lst.append(input())
    for j in range(i,i+1):
        print("Enter Score " + str(j+1))
        sub_lst.append(float(input()))
    lst.append(sub_lst)

print(lst)

Output:

[[R,88.0],[A,85.0],[S,78.0]]

Upvotes: 1

Related Questions