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]
Mr PizzaGuy
  • 410
  • 6
  • 19
luky
  • 2,263
  • 3
  • 22
  • 40

5 Answers5

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))
Tugay
  • 2,057
  • 5
  • 17
  • 32
  • 2
    Sidenote, [`l` is a bad variable name since it looks like `1` and `I`](https://www.python.org/dev/peps/pep-0008/#names-to-avoid). I would use `n` instead, personally. – wjandrea Jan 16 '21 at 22:16
3
[idx for idx, val in enumerate(['a', 'b'])]

output

[0, 1]
Albert G Lieu
  • 891
  • 8
  • 16
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.

Shane Bishop
  • 3,905
  • 4
  • 17
  • 47
  • 1
    [`range`](https://docs.python.org/3/library/functions.html#func-range) isn't a [generator](https://docs.python.org/3/glossary.html#term-generator) or even an [iterator](https://docs.python.org/3/glossary.html#term-iterator). It's actually a [sequence](https://docs.python.org/3/glossary.html#term-sequence). – wjandrea Jan 16 '21 at 22:22
1
enumerated_list = [(index, value) for index, value in enumerate(['a', 'b'])]
print(enumerated_list)

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

Dennis
  • 116
  • 1
  • 6
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.

Mr PizzaGuy
  • 410
  • 6
  • 19