What's the cleanest way to set up an enumeration in Python?

524 views Asked by At

I'm relatively new to Python and I was interested in finding out the simplest way to create an enumeration.

The best I've found is something like:

(APPLE, BANANA, WALRUS) = range(3)

Which sets APPLE to 0, BANANA to 1, etc.

But I'm wondering if there's a simpler way.

5

There are 5 answers

0
wim On BEST ANSWER

Enums were added in python 3.4 (docs). See PEP 0435 for details.

If you are on python 2.x, there exists a backport on pypi.

pip install enum34

Your usage example is most similar to the python enum's functional API:

>>> from enum import Enum
>>> MyEnum = Enum('MyEnum', 'APPLE BANANA WALRUS')
>>> MyEnum.BANANA
<MyEnum.BANANA: 2>

However, this is a more typical usage example:

class MyEnum(Enum):
    apple = 1
    banana = 2
    walrus = 3

You can also use an IntEnum if you need enum instances to compare equal with integers, but I don't recommend this unless there is a good reason you need that behaviour.

0
Ajay On

Using enumerate

In [4]: list(enumerate(('APPLE', 'BANANA', 'WALRUS'),1))
Out[4]: [(1, 'APPLE'), (2, 'BANANA'), (3, 'WALRUS')]

The answer by noob should've been like this

In [13]: from enum import Enum

In [14]: Fruit=Enum('Fruit', 'APPLE BANANA WALRUS')

enum values are distinct from integers.

In [15]: Fruit.APPLE
Out[15]: <Fruit.APPLE: 1>

In [16]: Fruit.BANANA
Out[16]: <Fruit.BANANA: 2>

In [17]: Fruit.WALRUS
Out[17]: <Fruit.WALRUS: 3>

As in your question using range is a better option.

In [18]: APPLE,BANANA,WALRUS=range(1,4)
1
Rahul Gupta On
a = ('APPLE', 'BANANA', 'WALRUS')

You can create a list of tuples using enumerate to get the desired output.

list(enumerate(a, start=1))
[(1, 'APPLE'), (2, 'BANANA'), (3, 'WALRUS')]

If you need 'APPLE' first and then 1, then you can do the following:

[(j, i +1 ) for i, j in enumerate(a)]
[('APPLE', 1), ('BANANA', 2), ('WALRUS', 3)]

Also, you can create a dictionary using enumerate to get the desired output.

dict(enumerate(a, start=1))
{1: 'APPLE', 2: 'BANANA', 3: 'WALRUS'}
4
Utsav T On

You can use this. Although slightly longer, much more readable and flexible.

from enum import Enum
class Fruits(Enum):
    APPLE = 1
    BANANA = 2
    WALRUS = 3

Edit : Python 3.4

0
Vikas Ojha On

You can use dict as well:

d = {
    1: 'APPLE',
    2: 'BANANA',
    3: 'WALRUS'
}