I want to append "," and then the item index to every item in a list of integers.

I know that I need to convert the integers to strings before I do that, but even if I do that, it isn't working:

(I use Python 3.7.3)

for element in mylist:
    element = str(element)
    element = "{0},".format(element)
    element = element + mylist.index(element)

What I want:

mylist = ["97,0", "569,1", "39,2", "230,3",....]

3 Answers

ShapeOfMatter On

Possibly someone can link to a question of which this is a duplicate, but I don't know my way around that well yet.

You want list comprehensions, and the enumerate function.

new_list = ["{0},{1}".format(item, index) for (index, item) in enumerate(old_list)]
HAhaJakub On
mylist = [97,0, 569,1, 39,2, 230,3]
for items in mylist:

Here is the solution to your question, if I understood it correctly you wanted to add for every item in the list "".

Adam Smith On

If you absolutely positively need to change the list in-place, then you can iterate over a copy of that list and do just that.

for i, val in enumerate(mylist[:]):  # note the empty slice there -- that creates a whole copy!
    mylist[i] = f"{val},{i}"

Technically since you're not adding or removing elements, you are allowed to do this without that copy

for i, val in enumerate(mylist):
    mylist[i] = f"{val},{i}"

but this is a dangerous habit to get into without fully understanding what you can and cannot do to a list that you're iterating over. If your goal was to do this but also remove the 10th element (or etc), you would have to make a copy. Similarly if you wanted to insert a new element before the value 97, or etc.

As general best practice, you should avoid mutating the list if possible and produce a new one using a list comprehension as recommended in ShapeOfMatter's answer