0

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]
5
  • There are no keys in a list.
    – progmatico
    Commented Jan 16, 2021 at 22:10
  • 1
    What do you mean by key of a list? Commented Jan 16, 2021 at 22:10
  • so its not possible with this syntactic sugar?
    – luky
    Commented Jan 16, 2021 at 22:10
  • @MitchellOlislagers key = order of the value in the list
    – luky
    Commented Jan 16, 2021 at 22:11
  • 1
    Does this answer your question? Accessing the index in 'for' loops?
    – wjandrea
    Commented Jan 16, 2021 at 22:12

5 Answers 5

4

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))
1
3
[idx for idx, val in enumerate(['a', 'b'])]

output

[0, 1]
3
  • 3
    Please do not use k, v. There are no keys and values in a list, OP is already confused about it. Maybe use index, element instead.
    – DeepSpace
    Commented Jan 16, 2021 at 22:15
  • it's just index as there is no key in the list object Commented Jan 16, 2021 at 22:15
  • I assume luky who asked the question is from another programming language field Commented Jan 16, 2021 at 22:17
1
enumerated_list = [(index, value) for index, value in enumerate(['a', 'b'])]
print(enumerated_list)

output: [(0, 'a'), (1, 'b')]

1
  • 1
    No need to unpack enumerate just to pack it again. Just do list(enumerate(['a', 'b']))
    – DeepSpace
    Commented Jan 16, 2021 at 22:27
1

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.

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.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.