0

I'm trying to find a way to print the position of every item in a list.

For example:

example_lst = ['dog', 'cat', 'plant']

print(example_lst.index(*))

Output:

>>> ['dog, 0', 'cat, 1', 'plant, 2']

Apologies if the example above is confusing.

Regardless, any help is greatly appreciated!

teddygraham
  • 117
  • 7
  • Please repeat [on topic]( https://stackoverflow.com/help/on-topic) and [how to ask]( https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour) – Prune Jul 29 '20 at 19:29
  • Just wrap the code in a for loop: `for item in example_lst: print(example_lst.index(item))` – marsnebulasoup Jul 29 '20 at 19:31
  • Don't forget, `index()` will give you the *first* match, if you have duplicates, it won't work. – SiHa Jul 29 '20 at 20:20

9 Answers9

3

Try compact list comprehension:

[f'{v} {i}' for i, v in enumerate(example_lst)]

Explanation:

This creates a list where each of the elements are determined by the for loop within.

In this loop, i is the index of the current element that the loop on and v is the value of that element.

for i, v in enumerate(example_lst)

This then joins the value and index together with

f'{v} {i}'

This is called an f-string (formatted string).

While this might look confusing, it is actually quite simple.

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. source

To make an f-string all that is needed is to place an f before the string. Then whatever is within curly braces is evaluated as python code.

So,

f'{v} {i}'

simply returns v + " " + i which is "dog 0", "cat 1" or "plant 2", depending on the position the loop is at.

Thus, you get your result is as desired.

['dog 0', 'cat 1', 'plant 2']
Community
  • 1
  • 1
ipj
  • 3,488
  • 1
  • 14
  • 18
2

Using a for loop is what you need. For loops iterate through each element in an array (among other things), so you can easily print the index of each element this way:

example_lst = ['dog', 'cat', 'plant']

for item in example_lst:
    print(example_lst.index(item))

In this example item is "dog" during the first iteration, "cat" during the second, and "plant" during the third. You can use this on longer lists too, because for loops iterate through the entire list.

But you want the index and the item at the same time.

To get your desired format, use enumerate:

example_lst = ['dog', 'cat', 'plant']

new_list = []

for (index, item) in enumerate(example_lst): #enumerate allows us to access the element and index of a list at the same time
    # Create a new list with the item and the index in each element
    elem = str(item) + " " + str(index) # str() converts items to strings so they can be joined
    new_list.append(elem)
    
print(new_list)
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
1
def func(list):
     ret = []
     for pos, val in enumerate(list):
         ret.append(f'{val}, {pos}')
     return ret

You just can simply construct a new list with this function and then return it. All this function does is loop over element in an array and simply construct a new list containing a string with the value comma the position - then returns the list. Hope this helped.

Alex
  • 151
  • 8
1

You can use the enumerate built-in function inside a list comprehension and This will do the job for you:

example = ['dog', 'cat', 'plant']

solution = [f"{value}, {key}" for key, value in enumerate(example)]

print(solution)

result:

['dog, 0', 'cat, 1', 'plant, 2']
0
example_lst = ['dog', 'cat', 'plant']
arr = []
for i, item in enumerate(example_lst):
    arr.append(f"{item}, {i}")
print(arr)

Output:

['dog, 0', 'cat, 1', 'plant, 2']
difurious
  • 1,523
  • 3
  • 19
  • 32
0

You can use list comprehension and string formatting to get your desired outcome like this.

example_lst = ['dog', 'cat', 'plant']
li = [f"{it}, {i}" for i, it in enumerate(example_lst)]
print(li)

result:

['dog, 0', 'cat, 1', 'plant, 2']
JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
-1
example_lst = ['dog', 'cat', 'plant']

print(example_lst.index('dog'))

Prints 0, since dog is in 0 position (start with 0), while

example_lst = ['dog', 'cat', 'plant']

print(example_lst.index('plant'))

Prints 2, since 'plant' is in 2 position. For your question, this would help.

example_lst = ['dog', 'cat', 'plant']
answer = []
for x in range(len(example_lst)):
  answer.append(example_lst[x] + ', '+ str(x))
print(answer)
MatthewProSkils
  • 364
  • 2
  • 13
-1

You can use enumerate. To give a simple example (leaving list comprehensions aside for simplicity):

example_lst = ['dog', 'cat', 'plant']
output = []
for idx, val in enumerate(example_lst):
   output.append(f'{val}, {idx}')
print(output)
michjnich
  • 2,796
  • 3
  • 15
  • 31
  • This results in a list like this: [0, 'dog', 1, 'cat', 2, 'plant'] (6 items in list) while the question is about getting a list like this: ['dog, 0', 'cat, 1', 'plant, 2'] (3 items in list). – JarroVGIT Jul 29 '20 at 19:38
  • Ah, sorry I'd missed the quotes. Just append a string then - I'll update the answer. – michjnich Jul 29 '20 at 20:00
-1

Try this:

example_lst = ['dog', 'cat', 'plant']
for i in example_lst:
    print(i, '-', example_lst.index(i))
Sanchez
  • 1
  • 3