541daw35d
541daw35d

Reputation: 151

Nested Python for loop only works with the last item in a list

I have encountered an issue where the 2nd for loop in a nested loop in Python only works for the last item in the list.

input = input("Words: ")
print(input)
list = input.split('[:,\s]')
print(list)

for each in list:
    for i, item in enumerate(list):
        joined = each + "TEST"
        print(joined)

As you can see in the code I am trying to loop through every item in the list and then in each loop of the loop before I want to append the string "TEST" to the end of the word that's currently looped through first loop.

Let's parse an input for example "aword, anotherword, yetanotherword, certainword". I would expect the program to produce the following output "awordTEST, anotherwordTEST, yetanotherwordTEST, certainwordTEST".

Instead this is the actual output "aword, anotherword, yetanotherword, certainwordTEST".

I can't figure out why does the 2nd loop only work for the last item in the list.

Edit: suggested solution was to use a single for loop. The thing is that I need to work with that 2nd for loop later and it is important for it to be in that 2nd for loop. Thanks.

Upvotes: 0

Views: 363

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155418

str.split does not accept regular expressions to split on. If you look at the contents of list, you'll see it's just the original string. If you want to split on a regex, you must use the re module:

import re

inp = input("Words: ")
print(inp)
lst = re.split(r'[:,\s]+', inp)
print(lst)

for each in lst:
    joined = each + "TEST"
    print(joined)

Try it online!

I removed the inner loop because it was doing nothing but multiplying outputs, and renamed variables to avoid name-shadowing built-ins.

Upvotes: 4

Hiroaki Genpati
Hiroaki Genpati

Reputation: 79

you need change this section:

for each in list:
    for i, item in enumerate(list):
        joined = each + "TEST"
    print(joined)

so the result is

awordTEST
anotherwordTEST
yetanotherwordTEST
certainwordTEST

Upvotes: -1

Related Questions