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.

omerbp
  • 3,973
  • 4
  • 31
  • 47
bob
  • 1,849
  • 2
  • 14
  • 26

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,495
  • 2
  • 23
  • 39
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
  • 302,178
  • 90
  • 548
  • 690
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
  • 4,831
  • 2
  • 21
  • 28
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
  • 43,515
  • 10
  • 102
  • 118
0

You can use dict as well:

d = {
    1: 'APPLE',
    2: 'BANANA',
    3: 'WALRUS'
}
Vikas Ojha
  • 6,318
  • 4
  • 21
  • 34