10

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.

0

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

4 Comments

Agreed on that. Python codestyle endorse explicit coding.
Just use the Enum initializer: Fruits = Enum('Fruits', 'APPLE BANANA WALRUS').
If we wish to have APPLE=654, BANANA = 980 and so on..?
@Noob The API supports that too: Fruits = Enum('Fruits', dict(APPLE=62, BANANA=980))
1

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) 

Comments

0

You can use dict as well:

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

Comments

0
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'} 

1 Comment

@downvoter Please explain the reason for the downvote. This way i can know what i have missed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.