List comprehension in python with numbering Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of List comprehension in python with numbering without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Suppose I have the following list:

temp = ['Ok', 'Whoa. Robot?']

How do I get a string that looks like

"1) 'Ok', 2) 'Whoa. Robot?'"

I’m trying to do this for a list comprehension. I can obviously join them using:

" ".join(temp)

I can do it in a loop in a fairly ugly way:

mystring = ""
temp = ['Ok', 'Whoa. Robot?']
for i in range(len(temp)):
    mystring += str(i) + ") " + temp[i] + "  "

Is there a pythonic way to do it in one step with a list comprehension?


mystring = ', '.join(["{}) {!r}".format(i, s) for i, s in enumerate(temp, 1)])

The {!r} conversion produces the repr() representation of the string, so you get quotes around the parts, but note that the quotes may change depending on the string’s content, or in other words if it contains quotes itself.

We are here to answer your question about List comprehension in python with numbering - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji