1

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.

2
  • Why are you adding elements to the same list1 you are iterating over? The for loop becomes an infinite loop Commented Jun 18, 2020 at 15:08
  • Thanks Devesh. You're right. A lame mistake on my part. Commented Jun 20, 2020 at 19:50

2 Answers 2

2

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:]))
Sign up to request clarification or add additional context in comments.

1 Comment

Damn. Such a lame mistake. Thanks! I never saw that. Thanks a lot!
1
for eachElement in list1:
    list1.append(str(int(eachElement)//2))

The loop body adds more elements to list1, so the for element in ... loop will never end.

1 Comment

Thank you John! It was a lame mistake on my part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.