1

This is my code so far:

things = ['humans', 'fish', 'plants', 'planets', 'stars']

print('These are types of things we learnt so far:')
for thing in things:
    print(thing, end=', ')
print()

print(len(things))
the_input = int(input('Now please enter a number which you want to print: '))
print(f'You have chosen {the_input} which is {things[the_input]}.')

# the unfinished rest:
# the_input = int(input('Now please enter a number which you want to print: '))
# if the_input == the index number of indexes of things list,
# then print:
# You have chosen {the_input} which is {things[the_input]}

This is my expected output:

These are types of things we learnt so far:
1) humans, 2) fish, 3) plants, 4) planets, 5) stars

Now please enter a number which you want to print:
2 # this is the input of terminal, not the output of print(the_input)
You have chosen 2 which is fish.

For this code I don't know how to do this (there maybe other issues but I'm not yet aware of them):

  1. The first print statement to show index_number) each_list_item
  2. to omit the last , which is shown in my code if you run it
Saeed
  • 3,255
  • 4
  • 17
  • 36
  • Does this answer your question? [Accessing the index in 'for' loops](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Dubious Denise Aug 15 '23 at 19:40

3 Answers3

3

Use enumerate and decrease index input:

things = ['humans', 'fish', 'plants', 'planets', 'stars']

print(*[f'{idx}) {thing}' for idx, thing in enumerate(things, 1)], sep=', ', end='\n\n')

the_input = int(input('Now please enter a number which you want to print:\n'))
print(f'You have chosen {the_input} which is {things[the_input-1]}.')

# 1) humans, 2) fish, 3) plants, 4) planets, 5) stars

# Now please enter a number which you want to print:
# 2
# You have chosen 2 which is fish.
Arifa Chan
  • 947
  • 2
  • 6
  • 23
2

Use combination of enumerate + str.join:

print('These are types of things we learnt so far:')
print(', '.join(f'{i}) {s}' for i, s in enumerate(things, 1)))

These are types of things we learnt so far:
1) humans, 2) fish, 3) plants, 4) planets, 5) stars
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

For this, you should use the enumerate method. As described by the Python documentation:

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

print('These are types of things we learnt so far:')
print(', '.join(f'{i}) {s}' for i, s in enumerate(things, start=1)))