How to say [:] programmatically in Python

Tags: python

I had a problem lately for how to pass in : programmatically into a function. I’d need either a specific element or all. Because of the program’s structure I really wanted to keep pass it as an argument into a function.

A simplified example:

>>> my_list = range(10)
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def selector(index):
...     return my_list[index]
...
>>> selector(0)
0
>>> selector(-1)
9

So how do I say [:]? Some things I tried:

>>> selector(None)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 2, in selector
TypeError: list indices must be integers, not NoneType
>>> selector(':')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 2, in selector
TypeError: list indices must be integers, not str

The solution: pass a built-in slice object:

>>> selector(slice(None))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Bingo!

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):