-4

There is something strange here below. If I were to change y.append(temp[-1]) to y.append(temp[1]). I would get an error message

y.append(temp[1]) IndexError: list index out of range

since I am indexing variable a, I should get the following temp value each time in the loop.

['350', '2']

['450', '9']

['570', '12']

['', '']

This should allow me to use temp[0] and temp[1]. Is this a bug?

x = []
y = []

a = ['350 5', '450 9', '570 12', '']

for index in range(len(a)):
    print(index)
    temp = a[index].split(" ")
    x.append(temp[0])
    y.append(temp[-1])

print(x)
print(y)
Uncle Bob
  • 1
  • 1
  • 6
    99.99% of the time, it's unwise to assume a bug with CPython. You're trying to split an empty string and assume you get 2 values. You don't – roganjosh Aug 03 '20 at 21:06
  • 1
    All you need to do is put `''.split()` into a REPL and see the output. It's an empty list – roganjosh Aug 03 '20 at 21:08

1 Answers1

1

The last item of your list does not contain a space, and thus the split function returns a list isn't only one value (which is an empty string). temp[1] points to an item that doesn't exist in temp.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • Djerro, thank you for your clear answer. It makes a lot of sense to me now. If it is an empty string why does -1 work? Shouldn't it be consistence and not work all together? This is the answer that I got using -1 indexing - ['350', '450', '570', ''] ['5', '9', '12', ''] – Uncle Bob Aug 03 '20 at 22:50