0

The list contains different sandwich ingredients, such as the following: ingredients=['snail', 'leeches',] and I have to create a loop that prints out the list(including the numbers: 1 snails 2 leeches

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42

2 Answers2

0

See this question, and answer: Accessing the index in 'for' loops?

Basically, you just use a for loop, but instead of looping over your collection, you loop over your collection processed by the enumerate function.

Here is an example using more advanced constructs like list comprehension:

ingredients = ["Foo", "Bar", "Baz"]
for line in [f"{i} {e}" for i, e in enumerate(ingredients)]:
    print(line)

It will print

0 Foo
1 Bar
2 Baz
Laurent Gabiot
  • 1,251
  • 9
  • 15
0

As you stated that you're asking about Python, so you need to use enumerate with a for loop as follows:

ingredients = ['snail', 'leeches']

for i, ingredient in enumerate(ingredients, 1):
    print(i, ingredient)

Note that the second argument of the enumerate function indicates the starting number, in this case, we need 1.

Watchanan
  • 419
  • 6
  • 13