Why can I use a list index as an indexing variable in a for loop? The 2019 Stack Overflow Developer Survey Results Are InHow does database indexing work?Finding the index of an item given a list containing it in PythonAccessing the index in 'for' loops?Understanding Python super() with __init__() methodsHow do I sort a dictionary by value?How to make a flat list out of list of lists?How do I pass a variable by reference?Loop through an array in JavaScriptHow do I list all files of a directory?Why is printing “B” dramatically slower than printing “#”?

How come people say “Would of”?

Falsification in Math vs Science

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

How do PCB vias affect signal quality?

The phrase "to the numbers born"?

Getting crown tickets for Statue of Liberty

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Why does the nucleus not repel itself?

What is the meaning of Triage in Cybersec world?

Why couldn't they take pictures of a closer black hole?

How to charge AirPods to keep battery healthy?

Why not take a picture of a closer black hole?

How much of the clove should I use when using big garlic heads?

Mathematics of imaging the black hole

Are spiders unable to hurt humans, especially very small spiders?

"as much details as you can remember"

How can I add encounters in the Lost Mine of Phandelver campaign without giving PCs too much XP?

Why is this code so slow?

How to type a long/em dash `—`

Did any laptop computers have a built-in 5 1/4 inch floppy drive?

Why can't devices on different VLANs, but on the same subnet, communicate?

Geography at the pixel level

Old scifi movie from the 50s or 60s with men in solid red uniforms who interrogate a spy from the past

Output the Arecibo Message



Why can I use a list index as an indexing variable in a for loop?



The 2019 Stack Overflow Developer Survey Results Are InHow does database indexing work?Finding the index of an item given a list containing it in PythonAccessing the index in 'for' loops?Understanding Python super() with __init__() methodsHow do I sort a dictionary by value?How to make a flat list out of list of lists?How do I pass a variable by reference?Loop through an array in JavaScriptHow do I list all files of a directory?Why is printing “B” dramatically slower than printing “#”?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








20















I have the following code:



a = [0,1,2,3]

for a[-1] in a:
print(a[-1])


The output is:



0
1
2
2


I'm confused about why a list index can be used as an indexing variable in a for a loop?










share|improve this question









New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 10





    Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

    – gameon67
    2 hours ago






  • 6





    I don't know why you would ever want to do this, but now I know you can

    – Nathan
    2 hours ago






  • 9





    This would be a great question for an awful coding interview

    – Nathan
    2 hours ago






  • 1





    OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

    – Christian Dean
    2 hours ago






  • 1





    This question first got two down votes :) I guess you shouldn't panic by down votes!

    – Amir A. Shabani
    2 hours ago

















20















I have the following code:



a = [0,1,2,3]

for a[-1] in a:
print(a[-1])


The output is:



0
1
2
2


I'm confused about why a list index can be used as an indexing variable in a for a loop?










share|improve this question









New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 10





    Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

    – gameon67
    2 hours ago






  • 6





    I don't know why you would ever want to do this, but now I know you can

    – Nathan
    2 hours ago






  • 9





    This would be a great question for an awful coding interview

    – Nathan
    2 hours ago






  • 1





    OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

    – Christian Dean
    2 hours ago






  • 1





    This question first got two down votes :) I guess you shouldn't panic by down votes!

    – Amir A. Shabani
    2 hours ago













20












20








20


8






I have the following code:



a = [0,1,2,3]

for a[-1] in a:
print(a[-1])


The output is:



0
1
2
2


I'm confused about why a list index can be used as an indexing variable in a for a loop?










share|improve this question









New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I have the following code:



a = [0,1,2,3]

for a[-1] in a:
print(a[-1])


The output is:



0
1
2
2


I'm confused about why a list index can be used as an indexing variable in a for a loop?







python for-loop indexing






share|improve this question









New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago









Christian Dean

15.8k62859




15.8k62859






New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 3 hours ago









Kundan VermaKundan Verma

1112




1112




New contributor




Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Kundan Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 10





    Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

    – gameon67
    2 hours ago






  • 6





    I don't know why you would ever want to do this, but now I know you can

    – Nathan
    2 hours ago






  • 9





    This would be a great question for an awful coding interview

    – Nathan
    2 hours ago






  • 1





    OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

    – Christian Dean
    2 hours ago






  • 1





    This question first got two down votes :) I guess you shouldn't panic by down votes!

    – Amir A. Shabani
    2 hours ago












  • 10





    Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

    – gameon67
    2 hours ago






  • 6





    I don't know why you would ever want to do this, but now I know you can

    – Nathan
    2 hours ago






  • 9





    This would be a great question for an awful coding interview

    – Nathan
    2 hours ago






  • 1





    OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

    – Christian Dean
    2 hours ago






  • 1





    This question first got two down votes :) I guess you shouldn't panic by down votes!

    – Amir A. Shabani
    2 hours ago







10




10





Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

– gameon67
2 hours ago





Somehow this question looks like a bad and newbie question, but I don't get the logic either lol

– gameon67
2 hours ago




6




6





I don't know why you would ever want to do this, but now I know you can

– Nathan
2 hours ago





I don't know why you would ever want to do this, but now I know you can

– Nathan
2 hours ago




9




9





This would be a great question for an awful coding interview

– Nathan
2 hours ago





This would be a great question for an awful coding interview

– Nathan
2 hours ago




1




1





OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

– Christian Dean
2 hours ago





OP, since it seems like your post may be gaining some traffic, I edited your post in an attempt to make your question clearer. If I'm misinterpreting your question, you can rollback the edit.

– Christian Dean
2 hours ago




1




1





This question first got two down votes :) I guess you shouldn't panic by down votes!

– Amir A. Shabani
2 hours ago





This question first got two down votes :) I guess you shouldn't panic by down votes!

– Amir A. Shabani
2 hours ago












6 Answers
6






active

oldest

votes


















19














To bring a language-lawyer aspect to the question, let's look at documentation:




for_stmt ::= "for" target_list "in" expression_list ":" suite


The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.




(emphasis not originally in docs)
The suite refers to the statements under the for-block, print(a[-1]) in our particular case.



Simply, on each iteration, the loop variable (target_list) gets assigned to the next item in the iterable (expression_list).



Let's extend the print statement:



a = [0, 1, 2, 3]
for a[-1] in a:
print(a, a[-1])


This gives the following output:



[0, 1, 2, 0] 0 # a[-1] assigned 0
[0, 1, 2, 1] 1 # a[-1] assigned 1
[0, 1, 2, 2] 2 # a[-1] assigned 2
[0, 1, 2, 2] 2 # a[-1] assigned itself (2)


As a[-1] is a valid form left-hand side, assignments to a[-1] will mutate a, modifying the list during iteration. In this particular example, a[-1] retains -2 from the previous evaluation. If we trace the assignment on each iteration, we have



a[-1] = 0 # a[0] # a[3] is 0 now
a[-1] = 1 # a[1] # a[3] is 1 now
a[-1] = 2 # a[2] # a[3] is 2 now
a[-1] = 2 # a[3] # a[3] is itself (2)





share|improve this answer




















  • 2





    Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

    – Mateen Ulhaq
    2 hours ago







  • 3





    Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

    – Christian Dean
    2 hours ago


















4














(this is more of a long comment than an answer - there are a couple of good ones already, especially @TrebledJ's. But I had to think of it explicitly in terms of overwriting variables that already have values before it clicked for me.)



If you had



x = 0
l = [1, 2, 3]
for x in l:
print(x)


you wouldn't be surprised that x is overriden each time through the loop. Even though x existed before, its value isn't used (i.e. for 0 in l:, which would throw an error). Rather, we assign the values from l to x.



When we do



a = [0, 1, 2, 3]

for a[-1] in a:
print(a[-1])


even though a[-1] already exists and has a value, we don't put that value in but rather assign to a[-1] each time through the loop.






share|improve this answer

























  • Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

    – Amir A. Shabani
    2 hours ago


















2














it is an interesting question, you can understand it by that:



for v in a:
a[-1] = v
print(a[-1])

print(a)


actually a becomes: [0, 1, 2, 2] after loop



output:



0
1
2
2
[0, 1, 2, 2]


Hope that helps you, and comment if you have further questions. : )






share|improve this answer






























    1














    The left expression of a for loop statement gets assigned with each item in the iterable on the right in each iteration, so



    for n in a:
    print(n)


    is just a fancy way of doing:



    for i in range(len(a)):
    n = a[i]
    print(n)


    Likewise,



    for a[-1] in a:
    print(a[-1])


    is just a fancy way of doing:



    for i in range(len(a)):
    a[-1] = a[i]
    print(a[-1])


    where in each iteration, the last item of a gets assigned with the next item in a, so when the iteration finally comes to the last item, its value got last assigned with the second-last item, 2.






    share|improve this answer






























      1














      a[-1] refers to the last element of a, in this case a[3]. The for loop is a bit unusual in that it is using this element as the loop variable.
      It's not evaluating that element upon loop entry, but rather it is assigning to it on each iteration through the loop.



      So first a[-1] gets set to 0, then 1, then 2. Finally, on the last iteration, the for loop retrieves a[3] which at that point is 2, so the list ends up as [0, 1, 2, 2].



      A more typical for loop uses a simple local variable name as the loop variable, e.g. for x .... In that case, x is set to the next value upon each iteration. This case is no different, except that a[-1] is set to the next value upon each iteration. You don't see this very often, but it's consistent.






      share|improve this answer

























      • How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

        – Amir A. Shabani
        2 hours ago






      • 1





        Agree, I don't really understand by reading this answer

        – gameon67
        2 hours ago











      • I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

        – Nathan
        2 hours ago











      • I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

        – Tom Karzes
        2 hours ago






      • 1





        "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

        – Christian Dean
        2 hours ago



















      0














      Coding interview from hell: Round two



      What is the output of the following?



      a=[1,2,3,4]
      for i,a[-i] in enumerate(a):
      print(a, i, a[-i])





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );






        Kundan Verma is a new contributor. Be nice, and check out our Code of Conduct.









        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55644201%2fwhy-can-i-use-a-list-index-as-an-indexing-variable-in-a-for-loop%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        19














        To bring a language-lawyer aspect to the question, let's look at documentation:




        for_stmt ::= "for" target_list "in" expression_list ":" suite


        The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.




        (emphasis not originally in docs)
        The suite refers to the statements under the for-block, print(a[-1]) in our particular case.



        Simply, on each iteration, the loop variable (target_list) gets assigned to the next item in the iterable (expression_list).



        Let's extend the print statement:



        a = [0, 1, 2, 3]
        for a[-1] in a:
        print(a, a[-1])


        This gives the following output:



        [0, 1, 2, 0] 0 # a[-1] assigned 0
        [0, 1, 2, 1] 1 # a[-1] assigned 1
        [0, 1, 2, 2] 2 # a[-1] assigned 2
        [0, 1, 2, 2] 2 # a[-1] assigned itself (2)


        As a[-1] is a valid form left-hand side, assignments to a[-1] will mutate a, modifying the list during iteration. In this particular example, a[-1] retains -2 from the previous evaluation. If we trace the assignment on each iteration, we have



        a[-1] = 0 # a[0] # a[3] is 0 now
        a[-1] = 1 # a[1] # a[3] is 1 now
        a[-1] = 2 # a[2] # a[3] is 2 now
        a[-1] = 2 # a[3] # a[3] is itself (2)





        share|improve this answer




















        • 2





          Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

          – Mateen Ulhaq
          2 hours ago







        • 3





          Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

          – Christian Dean
          2 hours ago















        19














        To bring a language-lawyer aspect to the question, let's look at documentation:




        for_stmt ::= "for" target_list "in" expression_list ":" suite


        The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.




        (emphasis not originally in docs)
        The suite refers to the statements under the for-block, print(a[-1]) in our particular case.



        Simply, on each iteration, the loop variable (target_list) gets assigned to the next item in the iterable (expression_list).



        Let's extend the print statement:



        a = [0, 1, 2, 3]
        for a[-1] in a:
        print(a, a[-1])


        This gives the following output:



        [0, 1, 2, 0] 0 # a[-1] assigned 0
        [0, 1, 2, 1] 1 # a[-1] assigned 1
        [0, 1, 2, 2] 2 # a[-1] assigned 2
        [0, 1, 2, 2] 2 # a[-1] assigned itself (2)


        As a[-1] is a valid form left-hand side, assignments to a[-1] will mutate a, modifying the list during iteration. In this particular example, a[-1] retains -2 from the previous evaluation. If we trace the assignment on each iteration, we have



        a[-1] = 0 # a[0] # a[3] is 0 now
        a[-1] = 1 # a[1] # a[3] is 1 now
        a[-1] = 2 # a[2] # a[3] is 2 now
        a[-1] = 2 # a[3] # a[3] is itself (2)





        share|improve this answer




















        • 2





          Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

          – Mateen Ulhaq
          2 hours ago







        • 3





          Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

          – Christian Dean
          2 hours ago













        19












        19








        19







        To bring a language-lawyer aspect to the question, let's look at documentation:




        for_stmt ::= "for" target_list "in" expression_list ":" suite


        The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.




        (emphasis not originally in docs)
        The suite refers to the statements under the for-block, print(a[-1]) in our particular case.



        Simply, on each iteration, the loop variable (target_list) gets assigned to the next item in the iterable (expression_list).



        Let's extend the print statement:



        a = [0, 1, 2, 3]
        for a[-1] in a:
        print(a, a[-1])


        This gives the following output:



        [0, 1, 2, 0] 0 # a[-1] assigned 0
        [0, 1, 2, 1] 1 # a[-1] assigned 1
        [0, 1, 2, 2] 2 # a[-1] assigned 2
        [0, 1, 2, 2] 2 # a[-1] assigned itself (2)


        As a[-1] is a valid form left-hand side, assignments to a[-1] will mutate a, modifying the list during iteration. In this particular example, a[-1] retains -2 from the previous evaluation. If we trace the assignment on each iteration, we have



        a[-1] = 0 # a[0] # a[3] is 0 now
        a[-1] = 1 # a[1] # a[3] is 1 now
        a[-1] = 2 # a[2] # a[3] is 2 now
        a[-1] = 2 # a[3] # a[3] is itself (2)





        share|improve this answer















        To bring a language-lawyer aspect to the question, let's look at documentation:




        for_stmt ::= "for" target_list "in" expression_list ":" suite


        The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed.




        (emphasis not originally in docs)
        The suite refers to the statements under the for-block, print(a[-1]) in our particular case.



        Simply, on each iteration, the loop variable (target_list) gets assigned to the next item in the iterable (expression_list).



        Let's extend the print statement:



        a = [0, 1, 2, 3]
        for a[-1] in a:
        print(a, a[-1])


        This gives the following output:



        [0, 1, 2, 0] 0 # a[-1] assigned 0
        [0, 1, 2, 1] 1 # a[-1] assigned 1
        [0, 1, 2, 2] 2 # a[-1] assigned 2
        [0, 1, 2, 2] 2 # a[-1] assigned itself (2)


        As a[-1] is a valid form left-hand side, assignments to a[-1] will mutate a, modifying the list during iteration. In this particular example, a[-1] retains -2 from the previous evaluation. If we trace the assignment on each iteration, we have



        a[-1] = 0 # a[0] # a[3] is 0 now
        a[-1] = 1 # a[1] # a[3] is 1 now
        a[-1] = 2 # a[2] # a[3] is 2 now
        a[-1] = 2 # a[3] # a[3] is itself (2)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 1 hour ago

























        answered 2 hours ago









        TrebledJTrebledJ

        3,85421329




        3,85421329







        • 2





          Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

          – Mateen Ulhaq
          2 hours ago







        • 3





          Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

          – Christian Dean
          2 hours ago












        • 2





          Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

          – Mateen Ulhaq
          2 hours ago







        • 3





          Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

          – Christian Dean
          2 hours ago







        2




        2





        Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

        – Mateen Ulhaq
        2 hours ago






        Might be useful to bold Each item [...] is assigned to the target list using the standard rules for assignments.

        – Mateen Ulhaq
        2 hours ago





        3




        3





        Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

        – Christian Dean
        2 hours ago





        Essentially, the important thing to note here is that Python considers a[-1] to be a valid form of the left-hand side of an assignment statement (e.g. a[-1] = 1 is valid grammar). Thus a[-1] is a valid "variable" name, because as the documentation stated, it evaluates the binding variable(s) in a for loop declaration as it would the left-hand side of an assignment.

        – Christian Dean
        2 hours ago













        4














        (this is more of a long comment than an answer - there are a couple of good ones already, especially @TrebledJ's. But I had to think of it explicitly in terms of overwriting variables that already have values before it clicked for me.)



        If you had



        x = 0
        l = [1, 2, 3]
        for x in l:
        print(x)


        you wouldn't be surprised that x is overriden each time through the loop. Even though x existed before, its value isn't used (i.e. for 0 in l:, which would throw an error). Rather, we assign the values from l to x.



        When we do



        a = [0, 1, 2, 3]

        for a[-1] in a:
        print(a[-1])


        even though a[-1] already exists and has a value, we don't put that value in but rather assign to a[-1] each time through the loop.






        share|improve this answer

























        • Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

          – Amir A. Shabani
          2 hours ago















        4














        (this is more of a long comment than an answer - there are a couple of good ones already, especially @TrebledJ's. But I had to think of it explicitly in terms of overwriting variables that already have values before it clicked for me.)



        If you had



        x = 0
        l = [1, 2, 3]
        for x in l:
        print(x)


        you wouldn't be surprised that x is overriden each time through the loop. Even though x existed before, its value isn't used (i.e. for 0 in l:, which would throw an error). Rather, we assign the values from l to x.



        When we do



        a = [0, 1, 2, 3]

        for a[-1] in a:
        print(a[-1])


        even though a[-1] already exists and has a value, we don't put that value in but rather assign to a[-1] each time through the loop.






        share|improve this answer

























        • Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

          – Amir A. Shabani
          2 hours ago













        4












        4








        4







        (this is more of a long comment than an answer - there are a couple of good ones already, especially @TrebledJ's. But I had to think of it explicitly in terms of overwriting variables that already have values before it clicked for me.)



        If you had



        x = 0
        l = [1, 2, 3]
        for x in l:
        print(x)


        you wouldn't be surprised that x is overriden each time through the loop. Even though x existed before, its value isn't used (i.e. for 0 in l:, which would throw an error). Rather, we assign the values from l to x.



        When we do



        a = [0, 1, 2, 3]

        for a[-1] in a:
        print(a[-1])


        even though a[-1] already exists and has a value, we don't put that value in but rather assign to a[-1] each time through the loop.






        share|improve this answer















        (this is more of a long comment than an answer - there are a couple of good ones already, especially @TrebledJ's. But I had to think of it explicitly in terms of overwriting variables that already have values before it clicked for me.)



        If you had



        x = 0
        l = [1, 2, 3]
        for x in l:
        print(x)


        you wouldn't be surprised that x is overriden each time through the loop. Even though x existed before, its value isn't used (i.e. for 0 in l:, which would throw an error). Rather, we assign the values from l to x.



        When we do



        a = [0, 1, 2, 3]

        for a[-1] in a:
        print(a[-1])


        even though a[-1] already exists and has a value, we don't put that value in but rather assign to a[-1] each time through the loop.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 hours ago









        Amir A. Shabani

        461616




        461616










        answered 2 hours ago









        NathanNathan

        2,06511326




        2,06511326












        • Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

          – Amir A. Shabani
          2 hours ago

















        • Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

          – Amir A. Shabani
          2 hours ago
















        Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

        – Amir A. Shabani
        2 hours ago





        Somehow I thought the variable used in for loop is immutable. +1 for pointing it out.

        – Amir A. Shabani
        2 hours ago











        2














        it is an interesting question, you can understand it by that:



        for v in a:
        a[-1] = v
        print(a[-1])

        print(a)


        actually a becomes: [0, 1, 2, 2] after loop



        output:



        0
        1
        2
        2
        [0, 1, 2, 2]


        Hope that helps you, and comment if you have further questions. : )






        share|improve this answer



























          2














          it is an interesting question, you can understand it by that:



          for v in a:
          a[-1] = v
          print(a[-1])

          print(a)


          actually a becomes: [0, 1, 2, 2] after loop



          output:



          0
          1
          2
          2
          [0, 1, 2, 2]


          Hope that helps you, and comment if you have further questions. : )






          share|improve this answer

























            2












            2








            2







            it is an interesting question, you can understand it by that:



            for v in a:
            a[-1] = v
            print(a[-1])

            print(a)


            actually a becomes: [0, 1, 2, 2] after loop



            output:



            0
            1
            2
            2
            [0, 1, 2, 2]


            Hope that helps you, and comment if you have further questions. : )






            share|improve this answer













            it is an interesting question, you can understand it by that:



            for v in a:
            a[-1] = v
            print(a[-1])

            print(a)


            actually a becomes: [0, 1, 2, 2] after loop



            output:



            0
            1
            2
            2
            [0, 1, 2, 2]


            Hope that helps you, and comment if you have further questions. : )







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 2 hours ago









            recnacrecnac

            1,279123




            1,279123





















                1














                The left expression of a for loop statement gets assigned with each item in the iterable on the right in each iteration, so



                for n in a:
                print(n)


                is just a fancy way of doing:



                for i in range(len(a)):
                n = a[i]
                print(n)


                Likewise,



                for a[-1] in a:
                print(a[-1])


                is just a fancy way of doing:



                for i in range(len(a)):
                a[-1] = a[i]
                print(a[-1])


                where in each iteration, the last item of a gets assigned with the next item in a, so when the iteration finally comes to the last item, its value got last assigned with the second-last item, 2.






                share|improve this answer



























                  1














                  The left expression of a for loop statement gets assigned with each item in the iterable on the right in each iteration, so



                  for n in a:
                  print(n)


                  is just a fancy way of doing:



                  for i in range(len(a)):
                  n = a[i]
                  print(n)


                  Likewise,



                  for a[-1] in a:
                  print(a[-1])


                  is just a fancy way of doing:



                  for i in range(len(a)):
                  a[-1] = a[i]
                  print(a[-1])


                  where in each iteration, the last item of a gets assigned with the next item in a, so when the iteration finally comes to the last item, its value got last assigned with the second-last item, 2.






                  share|improve this answer

























                    1












                    1








                    1







                    The left expression of a for loop statement gets assigned with each item in the iterable on the right in each iteration, so



                    for n in a:
                    print(n)


                    is just a fancy way of doing:



                    for i in range(len(a)):
                    n = a[i]
                    print(n)


                    Likewise,



                    for a[-1] in a:
                    print(a[-1])


                    is just a fancy way of doing:



                    for i in range(len(a)):
                    a[-1] = a[i]
                    print(a[-1])


                    where in each iteration, the last item of a gets assigned with the next item in a, so when the iteration finally comes to the last item, its value got last assigned with the second-last item, 2.






                    share|improve this answer













                    The left expression of a for loop statement gets assigned with each item in the iterable on the right in each iteration, so



                    for n in a:
                    print(n)


                    is just a fancy way of doing:



                    for i in range(len(a)):
                    n = a[i]
                    print(n)


                    Likewise,



                    for a[-1] in a:
                    print(a[-1])


                    is just a fancy way of doing:



                    for i in range(len(a)):
                    a[-1] = a[i]
                    print(a[-1])


                    where in each iteration, the last item of a gets assigned with the next item in a, so when the iteration finally comes to the last item, its value got last assigned with the second-last item, 2.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 2 hours ago









                    blhsingblhsing

                    43.5k41744




                    43.5k41744





















                        1














                        a[-1] refers to the last element of a, in this case a[3]. The for loop is a bit unusual in that it is using this element as the loop variable.
                        It's not evaluating that element upon loop entry, but rather it is assigning to it on each iteration through the loop.



                        So first a[-1] gets set to 0, then 1, then 2. Finally, on the last iteration, the for loop retrieves a[3] which at that point is 2, so the list ends up as [0, 1, 2, 2].



                        A more typical for loop uses a simple local variable name as the loop variable, e.g. for x .... In that case, x is set to the next value upon each iteration. This case is no different, except that a[-1] is set to the next value upon each iteration. You don't see this very often, but it's consistent.






                        share|improve this answer

























                        • How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                          – Amir A. Shabani
                          2 hours ago






                        • 1





                          Agree, I don't really understand by reading this answer

                          – gameon67
                          2 hours ago











                        • I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                          – Nathan
                          2 hours ago











                        • I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                          – Tom Karzes
                          2 hours ago






                        • 1





                          "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                          – Christian Dean
                          2 hours ago
















                        1














                        a[-1] refers to the last element of a, in this case a[3]. The for loop is a bit unusual in that it is using this element as the loop variable.
                        It's not evaluating that element upon loop entry, but rather it is assigning to it on each iteration through the loop.



                        So first a[-1] gets set to 0, then 1, then 2. Finally, on the last iteration, the for loop retrieves a[3] which at that point is 2, so the list ends up as [0, 1, 2, 2].



                        A more typical for loop uses a simple local variable name as the loop variable, e.g. for x .... In that case, x is set to the next value upon each iteration. This case is no different, except that a[-1] is set to the next value upon each iteration. You don't see this very often, but it's consistent.






                        share|improve this answer

























                        • How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                          – Amir A. Shabani
                          2 hours ago






                        • 1





                          Agree, I don't really understand by reading this answer

                          – gameon67
                          2 hours ago











                        • I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                          – Nathan
                          2 hours ago











                        • I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                          – Tom Karzes
                          2 hours ago






                        • 1





                          "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                          – Christian Dean
                          2 hours ago














                        1












                        1








                        1







                        a[-1] refers to the last element of a, in this case a[3]. The for loop is a bit unusual in that it is using this element as the loop variable.
                        It's not evaluating that element upon loop entry, but rather it is assigning to it on each iteration through the loop.



                        So first a[-1] gets set to 0, then 1, then 2. Finally, on the last iteration, the for loop retrieves a[3] which at that point is 2, so the list ends up as [0, 1, 2, 2].



                        A more typical for loop uses a simple local variable name as the loop variable, e.g. for x .... In that case, x is set to the next value upon each iteration. This case is no different, except that a[-1] is set to the next value upon each iteration. You don't see this very often, but it's consistent.






                        share|improve this answer















                        a[-1] refers to the last element of a, in this case a[3]. The for loop is a bit unusual in that it is using this element as the loop variable.
                        It's not evaluating that element upon loop entry, but rather it is assigning to it on each iteration through the loop.



                        So first a[-1] gets set to 0, then 1, then 2. Finally, on the last iteration, the for loop retrieves a[3] which at that point is 2, so the list ends up as [0, 1, 2, 2].



                        A more typical for loop uses a simple local variable name as the loop variable, e.g. for x .... In that case, x is set to the next value upon each iteration. This case is no different, except that a[-1] is set to the next value upon each iteration. You don't see this very often, but it's consistent.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 2 hours ago

























                        answered 3 hours ago









                        Tom KarzesTom Karzes

                        11.2k1926




                        11.2k1926












                        • How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                          – Amir A. Shabani
                          2 hours ago






                        • 1





                          Agree, I don't really understand by reading this answer

                          – gameon67
                          2 hours ago











                        • I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                          – Nathan
                          2 hours ago











                        • I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                          – Tom Karzes
                          2 hours ago






                        • 1





                          "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                          – Christian Dean
                          2 hours ago


















                        • How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                          – Amir A. Shabani
                          2 hours ago






                        • 1





                          Agree, I don't really understand by reading this answer

                          – gameon67
                          2 hours ago











                        • I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                          – Nathan
                          2 hours ago











                        • I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                          – Tom Karzes
                          2 hours ago






                        • 1





                          "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                          – Christian Dean
                          2 hours ago

















                        How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                        – Amir A. Shabani
                        2 hours ago





                        How does it actually gets set to 0, then 1, then 2 and finally 2? That's the confusing part!

                        – Amir A. Shabani
                        2 hours ago




                        1




                        1





                        Agree, I don't really understand by reading this answer

                        – gameon67
                        2 hours ago





                        Agree, I don't really understand by reading this answer

                        – gameon67
                        2 hours ago













                        I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                        – Nathan
                        2 hours ago





                        I expected it would be like saying for 3 in a: print(a[-1]) (because a[-1] was 3 at the start of the loop) and give an error, but clearly that's not the case. You're obviously correct about what's happening, but I'm surprised this evaluates this way.

                        – Nathan
                        2 hours ago













                        I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                        – Tom Karzes
                        2 hours ago





                        I've expanded the answer to explain more precisely how this works. Hopefully people will understand it this time.

                        – Tom Karzes
                        2 hours ago




                        1




                        1





                        "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                        – Christian Dean
                        2 hours ago






                        "The for loop is a bit unusual in that it is using this element as the loop variable." - This may be where the confusion is coming from. Python isn't using the element a[-1] evaluates to, rather, it's using the index a[-1] itself. If you rephrase that statement, your answer becomes much more clear.

                        – Christian Dean
                        2 hours ago












                        0














                        Coding interview from hell: Round two



                        What is the output of the following?



                        a=[1,2,3,4]
                        for i,a[-i] in enumerate(a):
                        print(a, i, a[-i])





                        share|improve this answer



























                          0














                          Coding interview from hell: Round two



                          What is the output of the following?



                          a=[1,2,3,4]
                          for i,a[-i] in enumerate(a):
                          print(a, i, a[-i])





                          share|improve this answer

























                            0












                            0








                            0







                            Coding interview from hell: Round two



                            What is the output of the following?



                            a=[1,2,3,4]
                            for i,a[-i] in enumerate(a):
                            print(a, i, a[-i])





                            share|improve this answer













                            Coding interview from hell: Round two



                            What is the output of the following?



                            a=[1,2,3,4]
                            for i,a[-i] in enumerate(a):
                            print(a, i, a[-i])






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 37 mins ago









                            PushpendrePushpendre

                            367316




                            367316




















                                Kundan Verma is a new contributor. Be nice, and check out our Code of Conduct.









                                draft saved

                                draft discarded


















                                Kundan Verma is a new contributor. Be nice, and check out our Code of Conduct.












                                Kundan Verma is a new contributor. Be nice, and check out our Code of Conduct.











                                Kundan Verma is a new contributor. Be nice, and check out our Code of Conduct.














                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55644201%2fwhy-can-i-use-a-list-index-as-an-indexing-variable-in-a-for-loop%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                                Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                                Category:Tremithousa Media in category "Tremithousa"Navigation menuUpload media34° 49′ 02.7″ N, 32° 26′ 37.32″ EOpenStreetMapGoogle EarthProximityramaReasonatorScholiaStatisticsWikiShootMe