I get a IndexError: list index out of range Error

Tags: function, python, range

IÂ´m having some troubles on my code, that implements a function that verifies the lenght of a string and return that string with or without spaces.

If String b >= 15 return b

If strinf < 15 return “number os spaces until len(b)2 + string b

But I get a IndexError: list index out of range Error. I cannot figure out where or why.

Traceback:

============= RESTART: C:UserspboDesktopTrab_04.py =============

ascii_letters = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ Traceback (most recent call last):

File “C:UserspboDesktopTrab_04.py”, line 30, in o2.append(a(o1[e]))

IndexError: list index out of range

============= ============= ============= ============= =============

Thanks a lot for any possible help.

```  from random import seed
from random import randint
from random import choice
from string import ascii_letters

seed(930)

def a(b):

if(len(b)<15) :
s = "";
l = len(b)
while(len(s) + len(b) < 15) :
s += " "
s += b
return s
else:
return b

print("ascii_letters = " + ascii_letters)
o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
o2 = []
for e in range(9622):
o2.append(a(o1[e]))
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
for e in range(9):
print(o1[e] + "|")
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
for e in range(9):
print(o2[e] + "|")

x1 = ""
x2 = "a"
x3 = "abc"
x4 = "abcdefghijklmnopqrstuvwxyz"
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
print(x1 + "|")
print(x2 + "|")
print(x3 + "|")
print(x4 + "|")
print("000000000111111111122222222223333333333")
print("123456789012345678901234567890123456789")
print(a(x1) + "|")
print(a(x2) + "|")
print(a(x3) + "|")
print(a(x4) + "|")
```

It looks like your indentation is incorrect (see also What is Python Whitespace and how does it work?).

If you change the following:

```o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
```

to:

```o1 = []
for e in range(9622):
k = randint(1, 25)
s = ""
for l in range(k):
s = s + choice(ascii_letters)
o1.append(s)
```

Then, your code appears to work.

Source: stackoverflow