Search code examples
pythonlistindexingzipenumerate

Accesing a list using index while using zip and enumerate


This code gives the error 'string index out of range'. Why and how to fix this?

home=['asdf','0','5','1']


prarabdh=['moody','a','b','c']

for i, (a, b) in enumerate(zip(home, prarabdh)):
    if 'a'==b[i]:
        print b[i-1]

Solution

  • You are iterating over the list of strings, so a and b already are the strings. You don't need to use b[i]. You're getting an error because you're trying to access a position in the string that doesn't exist (since, e.g., element 2 in b only has length 1).

    I'm taking a guess that what you want inside the loop is:

    if 'a' == b:
        print prarabdh[i-1]
    

    That is, if you get to an element 'a' in prarabdh, you want to print the previous element. However, this will give a peculiar result (printing the last element in prarabdh) if the first element is an 'a'. Also, it's not clear why you're using zip in the first place, since you never make use of the first list in the loop (i.e., you don't use the variable a at all).