Appending items to a list not printing?

Viewed 62

Here is my code in Python:

lst = []
for line in sys.stdin:
    line = line.strip().split(" ")
    newtup = (int(line[0]), int(line[1]))
    lst.append(newtup)

print(lst)

This is my input:

3 2
0 0
5 7
0 2

I want my list to have all the tuples of my input, so like:

[(3, 2), (0, 0), (5, 7), (0, 2)]

I don't know where it went wrong that my list is just not printing. I know my code is working when I tried to print for each iteration and it worked:

lst = []
for line in sys.stdin:
    line = line.strip().split(" ")
    newtup = (int(line[0]), int(line[1]))
    lst.append(newtup)
    print(lst)


[(3, 2)]
[(3, 2), (0, 0)]
[(3, 2), (0, 0), (5, 7)]
[(3, 2), (0, 0), (5, 7), (0, 2)]

Is this a glitch in Python? Thanks.

2 Answers

sys.stdin is a stream that doesn't exactly have a set end for the loop to break on. I'd suggest adding a terminating character or some condition to know when to exit the loop and print received values:

import sys

lst = []
for line in sys.stdin:
    line = line.strip().split(" ")
    if line[0].lower() == 'q':
        break
    newtup = (int(line[0]), int(line[1]))
    lst.append(newtup)

print(lst)

You are not terminating the for loop. Add condition for terminating the for loop else your code is right. Here's a example:

import sys
counter = 1
lst =[]
for line in sys.stdin:
    line = line.strip().split(" ")
    newtup = (int(line[0]),int(line[1]))
    lst.apppend(newtup)
    if counter== 4:
        break
    counter += 1
 
 print(lst)
Related