Skip to content

NeoPixel list slicing seems unintuitive to use #155

@Sarioah

Description

@Sarioah

There are a couple of examples out there in the wild that suggest that list slicing can be a shortcut to setting many NeoPixel-compatible LEDs at once (one such example).

The gist seems to be that one can assign a colour to a sliced list, i.e. NeoPixel[::2] = (255, 0, 0) should set every second pixel to red.

In practice it seems like the slicing exposes a mostly plain tuple instead. Attempts to assign to it appear to invoke sequence unpacking on the colour, usually throwing a ValueError since the LHS and RHS have different lengths.

I've been able to assign a tuple of colours to a sliced NeoPixel list, but this seems pretty cumbersome to do every time...

Adafruit CircuitPython 8.1.0 on 2023-05-22; Seeed XIAO nRF52840 Sense with nRF52840
>>> import neopixel
>>> import board
>>> pix = neopixel.NeoPixel(board.D10, 32)
>>> pix.fill(0xFFFFFF)  # all 32 lights turn white
>>> pix[::2] = 0xFF0000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> pix[::2] = (255, 0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unmatched number of items on RHS (expected 16, got 3).
>>> pix[::2].fill
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'fill'
>>> pix[::2] = (255, 0, 0) * len(pix[::2])  # every second light turns red
>>>

The final statement works, but doesn't feel like this is the way the slicing implementation was supposed to be used. The examples I can find seem suggest I should be able to have a bare colour on the RHS.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions