List Indexing

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
Pettefar
Posts: 3
Joined: Fri May 14, 2021 8:23 pm

List Indexing

Post by Pettefar » Fri May 14, 2021 8:43 pm

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

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: List Indexing

Post by scruss » Fri May 14, 2021 11:35 pm

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'

hippy
Posts: 130
Joined: Sat Feb 20, 2021 2:46 pm
Location: UK

Re: List Indexing

Post by hippy » Sat May 15, 2021 9:46 am

Pettefar wrote:
Fri May 14, 2021 8:43 pm
I made a four part list from a string.split operation.
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.

Post Reply