0
list = []
word = 'hello'
for i in word:
    list.append(i)
for i in list:
    print(list.index(i))

output:

0 1 2 2 4

I dont know how to make the second 'l' to have an index of 3 instead of 2. rindex() does not work on for the code that I am making

John Gordon
  • 29,573
  • 7
  • 33
  • 58
Lxbb
  • 1
  • i dont know how to use stackoverflow and i dont know how to make my code look like actual code so my bad – Lxbb Mar 08 '22 at 01:46
  • 1
    `index()` returns the location of the _first_ item with that value. – John Gordon Mar 08 '22 at 01:46
  • Welcome to Stack Overflow. Please read [ask] and make sure you **ask a question** when posting here. If you simply want to get the indices for the elements as you iterate with a loop, see the linked duplicate. If the question is "why does `index`/`rindex` work this way", then you should answer that by *reading the documentation*. But more importantly: there is no possible way that `.index` could tell you the index of "the second 'l'" differently from "the first 'l'", because it has no way of knowing which one was passed in - all it sees is `'l'`. It is important to have a clear mental model. – Karl Knechtel Mar 08 '22 at 01:56
  • You should make sure you understand what *values* are, as well as variables, and make sure that you understand how functions and methods work, so that you can properly reason about the behaviour. Finally: re "i dont know how to make my code look like actual code so my bad" - **it is your responsibility** to learn these kinds of things before posting - on *any* web site, not just Stack Overflow. In our case, the relevant guide is [here](https://stackoverflow.com/help/formatting). – Karl Knechtel Mar 08 '22 at 01:57

2 Answers2

0

Since you're printing just the list indexes which (by definition) are 0 1 2 3 4, you could use a simple range() loop:

for i in range(len(mylist)):
    print(i)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

The index() method returns the position at the first occurrence of the specified value.

To have the index of all the elements you can do like this

_list = []
word = 'hello'
for i in word:
    _list.append(i)
for i in range(len(_list)):
    print(_list[i], _list.index(_list[i], i))
BiRD
  • 134
  • 1
  • 8