rab777hp
rab777hp

Reputation: 33

Why am I unable to modify a list element at the beginning?

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

Answers (4)

Jeff Mercado
Jeff Mercado

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

Dan Gerhardsson
Dan Gerhardsson

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

Fred Foo
Fred Foo

Reputation: 363627

Use a list comprehension.

newlist = ['literal' + x for x in oldlist]

Upvotes: 3

aweis
aweis

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

Related Questions