Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python integer infinity for slicing

I have defined a slicing parameter in a config file:

max_items = 10

My class slices a list according to this parameter:

items=l[:config.max_itmes]

When max_items = 0, I want all items to be taken from l. The quick and dirty way is:

config.max_items=config.max_items if config.max_items>0 else 1e7

Assuming that there will be less then 1e7 items. However, I don't fancy using magic numbers. Is there a more Pythonic way of doing it, like an infinity integer constant?

like image 306
Adam Matan Avatar asked Jul 17 '11 09:07

Adam Matan


People also ask

How do you get int infinity in Python?

Representing infinity as an Integer in python One can use float('inf') as an integer to represent it as infinity.

Can I slice integer in Python?

slice() Parametersstop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last element). step (optional) - Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

When slicing in Python What does the 2 in [:: 2 specify?

Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).


1 Answers

There is no "infinity integer constant" in Python, but using None in a slice will cause it to use the default for the given position, which are the beginning, the end, and each item in sequence, for each of the three parts of a slice.

>>> 'abc'[:None]
'abc'
like image 133
Ignacio Vazquez-Abrams Avatar answered Oct 20 '22 00:10

Ignacio Vazquez-Abrams