-3
import  itertools


Numb = 'abxxxc' 
L=list(itertools.permutations(list(Numb)))
L=[''.join(str(i) for i in x) for x in L]
K=L[::]

for i in range(len(L)):
    if K[i][-1] == 'x':
        del K[i]
print(L)

I have a code like this and when I run this it gives me an error.

if K[i][-1]=='x':
IndexError: list index out of range

and I have no idea why. I tried everything but still it gives me error.Can someone please help me to see where is my error ?

Edit:

L=list(itertools.permutations(list(Numb)))
L=[''.join(str(i) for i in x) for x in L]

for i in range(len(L)):
    if L[i][5] == 'x':
        del L[i]
print(L)
seVenVo1d
  • 368
  • 2
  • 7
  • 16

3 Answers3

2

L is 720 elements long. for i in range(len(L)) corresponds to for i in range(720) You delete elements from K, so at a certain moment, K is 432 elements long, and i is 432 (you are trying to take the 433nd element of a 432-long list)

Perhaps this should do the job ?

import  itertools


Numb = 'abxxxc'
L=list(itertools.permutations(list(Numb)))
L=[''.join(str(i) for i in x) for x in L]

K = [elt for elt in L if elt[-1] != 'x']

print(K)

You should usually try to avoid using del. It is better to construct a new list containing the elements you need.

Gelineau
  • 2,031
  • 4
  • 20
  • 30
2

It's a bad practice to delete elements while iterating a list. A better version will be:

K = [element for element in K if element[-1] != 'x']
2

You are erasing element from the list while you're iterating it, so there will be a point where you refear to an index that does not exist anymore.

You can solve this problem with list comprehension:

mylist = [K[x] for x in range(len(L)) if (K[x][-1] != 'x')]
Gsk
  • 2,929
  • 5
  • 22
  • 29