Home > Net >  Why is my for loop not iterating over every element? it just stops after the first?
Why is my for loop not iterating over every element? it just stops after the first?

Time:10-05

I am trying to get an input from user and checking if their input is in a list. If it is, I want to replace a blank list with the corresponding answer. i.e:

base = [1,2,3,1,2,3]
blank = [0,0,0,0,0,0]

if the guess was 2 it would look like:

base = [1,2,3,1,2,3]
blank = [0,2,0,0,2,0]

Here is my code:

base = [1,2,3,1,2,3]
x = len(base)
blank = ['0'] * x

g = int(input('Input a number: '))

for i in base:
    ind = base.index(i)
    if i is g:
        blank[ind] = base[ind]

print(base, '\n', blank)

CodePudding user response:

Because .index() is only giving you the first index of the item in the list. (I'm talking about line ind = base.index(i) in your loop)

Instead you can find all the indexes with a list comprehension, then iterate over it and assign g to them:

base = [1, 2, 3, 1, 2, 3]
blank = ["0"] * len(base)

g = int(input("Input a number: "))

indexes = [i for i, item in enumerate(base) if item == g]
for i in indexes:
    blank[i] = g

print(base)
print(blank)

output:

Input a number: 2
[1, 2, 3, 1, 2, 3]
['0', 2, '0', '0', 2, '0']

But, there is also another solution for this, you don't need to first create your blank list. Do it in one shot:

base = [1, 2, 3, 1, 2, 3]

g = int(input("Input a number: "))

blank = [g if item == g else "0" for item in base]

print(base)
print(blank)

Note: Do not use is for comparing int objects. use ==.

  • Related