Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the second variable work in "for i, j in enumerate" vs list[i]

I understand that it is for ‘index’, ‘value’ in enumerate, I thought that I could use the second variable as list[index] but it doesn’t seem to work as such, I was wondering what the difference was.

codeCopy = [1,2,1,1]
currentSequence = [2,1,2,2]
correctColor = 0

for i, n in enumerate(codeCopy):
    for a, b in enumerate(currentSequence):
        if n == b:
            correctColor += 1
            n = None
            b = None
            print("i:",i, a)
            break
            
print(currentSequence)
print(codeCopy)

which outputs their original values instead of their new value of ‘None’ but if I replace

n = None
b = None

to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

codeCopy[i] = None
currentSequence[a] = None

It turns them accordingly to ‘None’

>Solution :

which outputs their original values instead of their new value of ‘none’

It’s not supposed to do that. The values n and b, as returned by enumerate, are pointers to the objects, but setting them to None only changes what those variable names reference, rather than the actual object itself. (You’ll have to use memcpy-type magic to achieve this.)

Think of it like this:

>>> a = ['my', 'reference', 'to', 'a', 'list']
>>> b = a
>>> b[0] = 'this also changes a'  # b references the same object at a
>>> a
['this also changes a', 'reference', 'to', 'a', 'list']
>>> b = None  # this overwrites what b points to; it does not affect a
>>> a
['this also changes a', 'reference', 'to', 'a', 'list']

Suppose the program, in memory, looks like this:

address | value
100     | ['my', 'reference', 'to', 'a', 'list']  
101     | a -> 100 (list)
102     | b -> 100 (list)

When you change b, it doesn’t actually affect the actual object:

address | value
100     | ['my', 'reference', 'to', 'a', 'list']  
101     | a -> 100 (list)
102     | b -> 103 (None)  # does NOT set the value at 100 to None
103     | None  # implementation detail: small integers and None and other things are permanently kept somewhere in memory at initialization

If you want to modify the value that’s actually at the list, you need to do the_list[desired_index] = None.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading