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. 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? Commented Jan 16, 2021 at 22:10
  • @MitchellOlislagers key = order of the value in the list Commented Jan 16, 2021 at 22:11
  • 1
    Does this answer your question? Accessing the index in 'for' loops? 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))
Sign up to request clarification or add additional context in comments.

1 Comment

Sidenote, l is a bad variable name since it looks like 1 and I. I would use n instead, personally.
3
[idx for idx, val in enumerate(['a', 'b'])]

output

[0, 1]

3 Comments

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.
it's just index as there is no key in the list object
I assume luky who asked the question is from another programming language field
1
enumerated_list = [(index, value) for index, value in enumerate(['a', 'b'])]
print(enumerated_list)

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

1 Comment

No need to unpack enumerate just to pack it again. Just do list(enumerate(['a', 'b']))
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.

Comments

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 Comment

range isn't a generator or even an iterator. It's actually a sequence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.