Home > Net >  get output element by element when input a list
get output element by element when input a list

Time:12-30

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

CodePudding user response:

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=" ")

CodePudding user response:

Change your last lines:

try this:

print(test_list[i])

or this will work too:

for i in test_list:
    print(i)

CodePudding user response:

fist let's dissect your code flow:-

test_list = ["4", "7", "9"]

Then: len(test_list) is 3

So

for i in range(3):
    print(i)

This will result in:-

0 
1
2

You could get your printed desired output with:-

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

where print(ele) will print each number in your list.

  • Related