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))
l is a bad variable name since it looks like 1 and I. I would use n instead, personally.[idx for idx, val in enumerate(['a', 'b'])]
output
[0, 1]
k, v. There are no keys and values in a list, OP is already confused about it. Maybe use index, element instead.enumerated_list = [(index, value) for index, value in enumerate(['a', 'b'])]
print(enumerated_list)
output:
[(0, 'a'), (1, 'b')]
enumerate just to pack it again. Just do list(enumerate(['a', '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.