Search code examples
python-3.xfor-loopif-statementenumerate

How to translate enumerate() to a for loop in Python


I have the following code which finds the index of a guessed number from a long number, however I cannot use enumerate. What would the equivalent for loop look like for this:

guess = input()
long_number = ('5666')
a = [i for i, number in enumerate(long_number) if number == guess]
print(a)

e.g. Output: if guess = 5, then the output should be [0].

How would you do this using while, for and/or if functions only?


Solution

  • You can simply change the list comprehension to:

    a = [i for i in range(len(long_number)) if long_number[i] == guess]
    

    (in your code):

    guess = input()
    long_number = '5666'
    a = [i for i in range(len(long_number)) if long_number[i] == guess]
    print(a)
    

    The output will be identical to yours