For example, I have a list = ['a', 'b', 'c']
.
What I want is a list indexed(list) == [(1, 'a'), (2, 'b'), (3, 'c)]
.
Is there a builtin or module for this?
For example, I have a list = ['a', 'b', 'c']
.
What I want is a list indexed(list) == [(1, 'a'), (2, 'b'), (3, 'c)]
.
Is there a builtin or module for this?
You can use the built-in function enumerate to achieve that.
In [1]: a = ['a', 'b', 'c']
In [2]: b = [(idx, item) for idx,item in enumerate(a)]
In [3]: b
Out[3]: [(0, 'a'), (1, 'b'), (2, 'c')]
Note: the default indice would start with 0
, but you could try to add start=1
to config that, e.g.
In [4]: c = [(idx, item) for idx,item in enumerate(a, start=1)]
In [5]: c
Out[5]: [(1, 'a'), (2, 'b'), (3, 'c')]
Hope it helps.
You can enumerate it by doing the following,
for i,n in enumerate(list):
# where i is the index and n is the value of the list
You can do something like
indexed_list = [(i + 1, elem) for i, elem in enumerate(your_list)]
I'm assuming that you need the index to start from 1. Otherwise you can just do a list comprehension on the enumerate
results directly without adding 1 to the index.
EDIT: Updated according to @pault 's suggestion, i.e. using the built-in argument
indexed_list = [indexed for indexed in enumerate(your_list, 1)]
Or simply
indexed_list = list(enumerate(your_list, 1))
Indices in Python begin at 0
not 1
. You can do what you want by using the built-in zip()
function along with the count()
generator function in the itertools
module.
It's also necessary to explicitly convert zip()
's result to a list
if that's what you want (which is why I changed the name of your variable to my_list
to prevent it from "hiding" the built-in class with the same name — a good thing to always do):
from itertools import count
my_list = ['a', 'b', 'c']
indexed_my_list = list(zip(count(), my_list))
print(indexed_my_list) # -> [(0, 'a'), (1, 'b'), (2, 'c')]
It's unclear why you would need to do this because you can use the built-in enumerate()
function to get the indices whenever they're needed, as illustrated in a number of the other answers.
Code below is what you want:
>>>l = ['a', 'b', 'c']
>>>indl = [(i + 1, val) for i, val in enumerate(l)]
>>> indl
[(1, 'a'), (2, 'b'), (3, 'c')]
Edit: according to @pault's suggestion, code is changed as below:
>>> yourList = ['a', 'b', 'c']
>>> listInd = [(i, val) for i, val in enumerate(yourList, 1)]
>>> listInd
[(1, 'a'), (2, 'b'), (3, 'c')]
>>>
You can use enumerate and it's start argument for this too:
l = ['a', 'b', 'c']
indexed_list = list(enumerate(l, 1))
As for a function called indexed
you could make one
Note! Never replace a builtin keyword! list
list is one of them
>>> def indexed(l, start=1):
... return list(enumerate(l, start))
>>> l = ['a', 'b', 'c']
>>> indexed(l)
[(1, 'a'), (2, 'b'), (3, 'c)]
This defaults to a start value of 1.
Use list comprehension and enumerate
[(i,l) for i,l in enumerate(list)]