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.

AvidLearner
  • 4,123
  • 5
  • 35
  • 48
bob
  • 1,879
  • 2
  • 15
  • 27

5 Answers5

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

Utsav T
  • 1,515
  • 2
  • 24
  • 42
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.

wim
  • 338,267
  • 99
  • 616
  • 750
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)
Ajay
  • 5,267
  • 2
  • 23
  • 30
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'}
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
0

You can use dict as well:

d = {
    1: 'APPLE',
    2: 'BANANA',
    3: 'WALRUS'
}
Vikas Ojha
  • 6,742
  • 6
  • 22
  • 35