9

I currently have some code that reads like this:

letters = {
10 : "A",
11 : "B",
12 : "C",
13 : "D",
14 : "E",
15 : "F"
}
vallist = [rd1, rd2, gd1, gd2, bd1, bd2]
for i in vallist:
    if i >= 10:
        i = letters[i]

What I want to happen is the for loop to iterate through vallist and replace any value that is greater than 10 with its corresponding letter. However, my current code just changes i and not the original value in the list. For example, if rd1 is set to 15, the code runs through and i is set to "F", but rd1 does not change to "F", and instead just stays as 15. How can I fix this?

4 Answers 4

13

For each iteration of the for loop the variable i is assigned with just a copy of the value of an item in vallist, so changes made to i won't be reflected in i.

You should update the items of i via index, which you can generate with the enumerate function:

for index, value in enumerate(vallist):
    if value >= 10:
        vallist[index] = letters[value]
Sign up to request clarification or add additional context in comments.

1 Comment

I think this statement is not correct: "[...] the variable i is assigned with just a copy of the value of an item in vallist, [...]". According to Ned Batchelder's guide "Assignment never copies data". A for-loop is an assignment as well; in this case it makes i refer to a value already referenced by an item in vallist. It's the line i = letters[i] where now i refers to another value, in this case the value of letters[i], e.g. the string "A". There is no copying involved in the author's code example.
2
rd1, rd2, gd1, gd2, bd1, bd2 = 10, 11, 12, 13, 14, 9
letters = {
10 : "A",
11 : "B",
12 : "C",
13 : "D",
14 : "E",
15 : "F"
}
vallist = [rd1, rd2, gd1, gd2, bd1, bd2]
for index, value in enumerate(vallist):
    if value >= 10 and value <= 15:
        vallist[index] = letters[value]
print(vallist)

As mentioned in the other comment you need both the index and the value while looping over your vallist. so you can replace the value on the index with the value in your dictionary.

Comments

0
for i in range(len(vallist)):
    if vallist[i] >= 10:
        vallist[i] = letters[i]

Because in your case i is just a copy of the current item in vallist. But this way i will be an index, so you can modify your original list throught it.

Comments

0

actually i is the reference of that element of array and the value changes will not be affected to that element , instead try this,

# iterating through every index of array

for i in range(len(vallist)):
 if vallist[i] >= 10 and vallist[i]<=15:
      vallist[i] = letters[vallist[i]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.