Iteration in a List

Hello,

I have the following list of items. How can I print one after the other and number each item like:

Item 1 is
Item 2 is
Item 3 is…

items = [‘razor’, ‘toothbrush’, ‘comb’, ‘mirror’, ‘shoe’, ‘slippers’, ‘laptop’, ‘glasses’, ‘lotion’, ‘aftershave’]
for item in items:
print(f’Item is {item.title()}’)
print(f’Ron, please buy these’)

list =  ['razor' , 'toothbrush' , 'comb' , 'mirror' ,'shoe']
print('Ron, please buy these: ')
for i in list:      
	print(i)

Hi Yogibjorn,

Thanks for the reply but I want the output to print the items one after the other and itemize it like:
Item 1 is Razor
Item 2 is Toothbrush
Item 3 is Comb
And so on and so forth…

Below are a couple of approaches that you could use.

for i in range(len(items)):
  print(f'Item {i + 1} is {items[i].title()}.')
for i, item in enumerate(items):
  print(f'Item {i + 1} is {item.title()}.')

See:

3 Likes

Thanks Quercus,

Both codes worked perfectly. Kudos !!!

Regards,

Eagle Eye

1 Like

You are welcome.

Please remember to format posted code. This will do it:

  • Copy the original code.
  • Paste it into your post.
  • Select it.
  • Click the </> button above the editing window.

This is unformatted code:

for i, item in enumerate(items):
print(f’Item {i + 1} is {item.title()}.’)

This is formatted code:

for i, item in enumerate(items):
  print(f'Item {i + 1} is {item.title()}.')

Which one looks better?

2 Likes

Thanks Quercus,

I found the icon…the no 6th from the left. I use this in SAP ABAP very well, am just new to Python. Much appreciated.

Eagle Eye

1 Like

You can avoid adding 1 to every index:

for index, item in enumerate(items, start=1):
    print(f'Item {index} is {item.title()}.')

@Quercus The first approach (iterating range(len(items))) is a bad style in Python. It is better to iterate list directly instead of accessing individual items through the indexing operator []. The code is then more generic and can accept any iterable type not just number-indexable types.

Please pay attention to not re-assing / shadow builtins. The builtin list is being used very often. For example this expression generates list of numbers 0 - 9:

list(range(10))
1 Like

…re-assigning / shadowing…

Václav is pointing out that list or list() is already used and should be treated as a reserved name.

Excellent point. The user IN THIS POST capitalized List so that it was unique, but was still a risky (not good) practice.