I made a four part list from a string.split operation.
When I try and access it it says that List[2] is an “index too large” error. I have to use List[-2] instead. Similarly with List[3] and List[-1]. Am I somehow missing something?
I am using Thonny on a RPi 4 to program my Pico.
Nick
Dublin
List Indexing
Re: List Indexing
What was your string, and what parameters did you give to split?
Code: Select all
MicroPython v1.15 on 2021-05-06; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>> string="one two three four"
>>> a=string.split()
>>> len(a)
4
>>> a
['one', 'two', 'three', 'four']
>>> a[2]
'three'
>>> a[3]
'four'
>>> a[-1]
'four'
>>> a[-2]
'three'
>>> a[1]
'two'
>>> a[0]
'one'
Re: List Indexing
It seems you didn't, even though you intended to. If List[2] has an "index too large" that indicates you only created, at most, a two part list; List[0] and List[1].
It seems you have a two part list: List[-1] is the last in the list, equates to List[1], List[-2] is the one before that, equates to List[0], which is why those work.
Add a print(List) after you create the list to see what's actually in it.