Home > Software design >  How to create a loop that prints out a given list (including numbers)
How to create a loop that prints out a given list (including numbers)

Time:10-28

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related