Eric Evans
Eric Evans

Reputation: 672

Create cli numerated menu from list

I have a list that all I want is a menu printed out of all the partitions that are stored in mylist. I would like it to look like this

1: /dev/sda0
2: /dev/sda1
3: /dev/sda2
etc....

This is what I have so far.

import pyudev

mylist = [device.devide_node for device in context.list_devices(subsystem='block', DEVTYPE='partitions')]

for x in mylist:
     print mylist[len(x)] + ': ' + mylist

I don't know how to format this to make it look like above

Upvotes: 0

Views: 44

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122091

Your current code:

for x in mylist:
    print mylist[len(x)]

Makes very little sense. x is an item in the list, len(x) is the length of that item (e.g. len("/dev/sda0") == 9), and you are trying to use that length as an index into the list. This is likely to lead to an IndexError, as there is no guarantee that mylist[9] exists!

I think you were trying to do something like:

for x in range(len(mylist)):
    print mylist[x]

where x would be a valid index for mylist, but it is much better to use enumerate for this type of process:

for num, device in enumerate(mylist, 1):
    print "{0}: {1}".format(num, device)

Upvotes: 0

nneonneo
nneonneo

Reputation: 179552

Use enumerate:

for i, x in enumerate(mylist):
    print '{}: {}'.format(i+1, x)

Upvotes: 1

Related Questions