Reputation: 845
I have a list
in python
- ['item1','item2','item3','item4']
. I am trying to print this list in following way - 1. ITEMS: item1 2. ITEMS: item2 3. ITEMS: item3 4. ITEMS: item4
. I wrote this code but this is giving error as I am trying to specify range()
in wrong way:
list_semi = ["%d. ITEMS: %s" % (x for x in range(1,len(bookings)),items) for items in bookings]
print('Your items are {}.'.format(','.join(list_semi)))
bookings
in the above code is the list whose sample data I have posted above. How can I print the list in the desired way as I have mentioned above?
UPDATE CASE 2 If my sample input list changes to - [[item1,price1],[item2,price2]...]
and I want the sample output as 1. ITEMS: item1, PRICE: price1 2. ITEMS: item2, PRICE: price2 3. ITEMS: item3, PRICE: price3 4. ITEMS: item4, PRICE: price4
then how should I frame my code? the list name is same as bookings
Upvotes: 1
Views: 989
Reputation: 78546
No need to use range
. Iterate on the list object directly, using enumerate
to generate the indices. Specify the start parameter as 1:
>>> ' '.join(['{}. ITEMS: {}'.format(i, x) for i, x in enumerate(lst, 1)])
'1. ITEMS: item1 2. ITEMS: item2 3. ITEMS: item3 4. ITEMS: item4'
Update:
>>> lst = [['item1','price1'],['item2','price2']]
>>> ' '.join(['{}. ITEMS: {}, PRICE: {}'.format(i, *x) for i, x in enumerate(lst, 1)])
'1. ITEMS: item1, PRICE: price1 2. ITEMS: item2, PRICE: price2'
Upvotes: 4