Search code examples
pythonlistoutput

get output element by element when input a list


enter image description hereI want to enter numbers separated by spaces as input. Store the numbers in a list and get the elements by elements in that list as output.

This was my code.

lst = input()
test_list =[]

for ele in lst.split():
    n_int = int(ele)
    test_list.append(n_int)

for i in range(len(test_list)):
    print(i)

When I enter a input like 4 7 9, I expect an output like this. 4 7 9 But I get this output 0 1 2


Solution

  • You are using range() function which helps to go index by index in list if you wanted to go item by item you don't need to use range() you can simply access items by iterating see the below code..

    for i in test_list:
        print(i)
    

    You can also do with range() function simple accessing list by index and print..

    for i in range(len(test_list)):
        print(test_list[i])
    

    The above 2 solutions will give output

    3
    7
    9 
    

    If you wanted in same line like 3 7 9 you can use end in print

    print(i,end=" ")    or    print(test_list[i],end=" ")