PYTHON error index out of range

Asked

Viewed 47 times

-1

There I was trying to create a script that did permutation, create a combination of the list items in a new list. Follow the python code:

itens = []
while True:
          adition = input('Coloque os itens: ')
          if adition == 'end':
                    break
          else:
                    itens.append(adition)
                    print(adition)
comb = []

for i in itens:
           contagem = 0
           while True:
                     comb.append(i + itens[contagem])
                     print(comb)
                     if contagem == len(itens):
                               break
                     else:
                               contagem = contagem + 1

But when I run the command and put the items in the list returns the following error:

Comb.append(i+items[count])

Indexerror: list index out of range

1 answer

1

Elevate the condition if contagem == len(itens) to run before accessing itens[contagem]

while True:
    if contagem == len(itens):
        break
    else:
        comb.append(i + itens[contagem])
        print(comb)
        contagem = contagem + 1

The error happens in your code because you try to access the position contagem from your list before validating whether it is valid.


Suppose that itens own both items: a and b.

In the first iteration cont is equal to 0

He picks up a at position 0 and generates aa

In the second iteration cont is equal to 1

He picks up b at position 1 and generates ab

In the third iteration cont is equal to 2

He tries to pick up the item at position 2, which does not exist, and so the error.


A simpler way of writing this logic would be

while contagem < len(itens):
    comb.append(i + itens[contagem])
    print(comb)
    contagem = contagem + 1

Or use another loop for

for i in itens:
    for i2 in itens:
        comb.append(i + i2)
        print(comb)
  • Thank you very much! I didn’t know while worked like this. Just one more question. Why can’t my code test all combinations? If a list has [ 1, 2, 3, 4], the code only forms 11, 12, 13, 14 and not 11,12,13,14,21,22,23,24... and so on. Why this happens if I used the for i in list to read all the list items and create a new combination for each of them?

  • The code forms all permutations, maybe you made another mistake when fixing it, see it working here

  • Fixed. In the code when I was correcting, I counted before the for, this stopped the loop of repetition since counting did not reset. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.