-5

im a bit confused, I have a list of 20 items, and I attempt to get the 20th one. But I get an error

example:

abc = 'abcdefghijklmnopqrstuvwxyz'
l = list()
for n in range(0, 20):
    l.append(abc[n])
print(l[19+1])

but I get an indexError can someone tell me why?

Michael
  • 37
  • 9

2 Answers2

1

You are making a list with length 20, so you cannot index element [20], you can only index [0] through [19]

Note that as a side note, an easier way to do what you are trying to do is with slicing.

>>> l = abc[0:20]
>>> l
'abcdefghijklmnopqrst'
>>> l[19]
't'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

As the others have noted, your list indices begin with zero, making 19 the last element.

Another related thing you might want to consider doing is instead of getting a range from 0 to 19, do this instead:

for n in range(len(mylist)):

The len function returns 20, and when fed 20 the range function will return an iterable from 0 to 19.

Rick
  • 43,029
  • 15
  • 76
  • 119