Search code examples
pythoninputsplitfreeze

Python - Simple input program is hanging at input statement


I'm writing a simple program that takes 5 numbers, puts them in a list, divides each number by 2 and prints the output list.

list1 = input("Type 5 numbers: ").split()
for eachElement in list1:
    list1.append(str(int(eachElement)//2))
print("final numbers are "," ".join(list1[5:]))

PROBLEM: The program hangs after the first input line. In the terminal, it takes the 5 numbers but never goes onto the next line.

Type 5 numbers: 56 67 84 45 78


What can be the problem? I have used input with split in many other programs, but it hangs sometimes and works most of the time.


Solution

  • You're iterating over your list and appending to it at the same time, meaning your list grows into infinity.

    Observe what happens when you print something inside the loop body:

    list1 = input("Type 5 numbers: ").split()
    for eachElement in list1:
        val = str(int(eachElement)//2)
        print("Appending", val)
        list1.append(val)
    print("final numbers are "," ".join(list1[5:]))
    

    This prints:

    Type 5 numbers: 1 2 3 4 5
    Appending 0
    Appending 1
    Appending 1
    Appending 2
    Appending 2
    Appending 0
    Appending 0
    Appending 0
    ...
    

    You can fix this by putting the new numbers in a different list, first:

    list1 = input("Type 5 numbers: ").split()
    list2 = []
    for eachElement in list1:
        val = str(int(eachElement)//2)
        print("Appending", val)
        list2.append(val)
    list1.extend(list2)
    print("final numbers are "," ".join(list1[5:]))