Reputation: 33
I have a list and I would like to make a new list where newlist[i] = 'literal' + oldlist[i]
.
I have tried code like:
i = 1
for elem in oldlist:
newlist[i] = 'literal' + oldlist[i]
i += 1
i = 1
for elem in newlist:
elem = 'literal' + oldlist[i]
i += 1
and many similar attempts yet keep getting errors such as "can't assign to function call" and others. How should my code be?
Upvotes: 0
Views: 122
Reputation: 134891
Lists are zero-based meaning the first item in the list is at index 0
.
e.g.,
l = [1, 2, 3, 4, 5]
print(l[0]) # 1
print(l[1]) # 2
You are starting your indexing at 1
hence your first item never gets changed.
Though your code doesn't fit the canonical "indexed-loop" format. It should look more like this:
for i in range(len(oldlist)):
newlist[i] = 'literal' + oldlist[i]
But an even better way to do this is to use a list comprehension:
newlist = ['literal' + olditem for olditem in oldlist]
Upvotes: 4
Reputation: 1889
Try a list comprehension:
newlist = [item + literal for item in oldlist]
Also, remember that list indices are numbered starting at zero, which means that the maximum index equals len(list) - 1
Upvotes: 1
Reputation: 363627
Use a list comprehension.
newlist = ['literal' + x for x in oldlist]
Upvotes: 3
Reputation: 5596
because the elem
is the value in the list and not a reference to the location in the list. (i reference the second example you have)
Upvotes: 1