This syntax is able to define new list above list (or array):
[v for v in ['a', 'b']]
But how to get the index of the list? This doesn't work
[k for k, v in ['a', 'b']]
Expected output
[0, 1]
This syntax is able to define new list above list (or array):
[v for v in ['a', 'b']]
But how to get the index of the list? This doesn't work
[k for k, v in ['a', 'b']]
Expected output
[0, 1]
Probably you have meant indexes, as there are no keys in list. We can get them like this:
indexes = [index for index,element in enumerate(your_list)]
But this isn't really necessary, we can get length of the list and get indexes from it as indexes are from 0 to [length of list]-1:
length = len(your_list)
indexes = list(range(length))
[idx for idx, val in enumerate(['a', 'b'])]
output
[0, 1]
You can use range()
:
range(len(['a', 'b']))
range()
will return a sequence. If you need a list specifically, you can do
list(range(len(['a', 'b'])))
As mentioned in the comments, in python lists do not have keys.
enumerated_list = [(index, value) for index, value in enumerate(['a', 'b'])]
print(enumerated_list)
output:
[(0, 'a'), (1, 'b')]
I think you meant index
. Remember that lists have no keys, those are dictionaries.
[index for index, value in enumerate(['a', 'b'])]
The enumerate
function is basically range
but it returns the index and the value.
Read more on enumerate
here.