Python list append behavior [duplicate]












17
















This question already has an answer here:




  • List of lists changes reflected across sublists unexpectedly

    12 answers




Don't really know how to formulate the question...



Suppose I do the following:



    >>> l = []*2
>>> l
[, ]
>>> l[0].append(1)
>>> l
[[1], [1]]


Why does 1 gets appended to both lists?










share|improve this question













marked as duplicate by vaultah python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 13 '17 at 15:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 4





    This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

    – glglgl
    Aug 31 '11 at 10:05
















17
















This question already has an answer here:




  • List of lists changes reflected across sublists unexpectedly

    12 answers




Don't really know how to formulate the question...



Suppose I do the following:



    >>> l = []*2
>>> l
[, ]
>>> l[0].append(1)
>>> l
[[1], [1]]


Why does 1 gets appended to both lists?










share|improve this question













marked as duplicate by vaultah python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 13 '17 at 15:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 4





    This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

    – glglgl
    Aug 31 '11 at 10:05














17












17








17


2







This question already has an answer here:




  • List of lists changes reflected across sublists unexpectedly

    12 answers




Don't really know how to formulate the question...



Suppose I do the following:



    >>> l = []*2
>>> l
[, ]
>>> l[0].append(1)
>>> l
[[1], [1]]


Why does 1 gets appended to both lists?










share|improve this question















This question already has an answer here:




  • List of lists changes reflected across sublists unexpectedly

    12 answers




Don't really know how to formulate the question...



Suppose I do the following:



    >>> l = []*2
>>> l
[, ]
>>> l[0].append(1)
>>> l
[[1], [1]]


Why does 1 gets appended to both lists?





This question already has an answer here:




  • List of lists changes reflected across sublists unexpectedly

    12 answers








python list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 31 '11 at 10:00









AsteriskAsterisk

2,48622850




2,48622850




marked as duplicate by vaultah python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 13 '17 at 15:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by vaultah python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 13 '17 at 15:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 4





    This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

    – glglgl
    Aug 31 '11 at 10:05














  • 4





    This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

    – glglgl
    Aug 31 '11 at 10:05








4




4





This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

– glglgl
Aug 31 '11 at 10:05





This issue is discussed in docs.python.org/faq/programming.html#id38 resp. docs.python.org/faq/….

– glglgl
Aug 31 '11 at 10:05












4 Answers
4






active

oldest

votes


















17














[]*2 is a list of two references to the same list. You are appending to it and then seeing it twice.






share|improve this answer































    12














    Because there is really only one list. Consider this:



    >>> l = []
    >>> l2 = l*2
    >>> l2[0] is l[0]
    True
    >>> l2[1] is l[0]
    True


    *2 performed on a list does not copy the list but return a list of length 2 filled with the same reference.



    What you probably wanted was this:



    >>> l = [ for _ in xrange(2)]


    As @Asterisk mentions in a comment, the same behaviour is exposed by all common collections. As a rule of thumb it is therefore best to only use multiplication on immutable types with value-semantics.






    share|improve this answer


























    • it seems *2 performed on dictionary does not copy as well...

      – Asterisk
      Aug 31 '11 at 10:13











    • and sets........

      – Asterisk
      Aug 31 '11 at 10:21



















    1














    Here's how i initialize a list of lists. Rows vary slowest.



    nrows = 3; ncols = 5

    l_of_ls = [[0]*ncols for i in range(nrows )]

    for rix, r in enumerate(l_of_ls):
    for cix, c in enumerate(r):
    print rix, cix, 'val = ',c


    RESULT



    0 0 val =  0
    0 1 val = 0
    0 2 val = 0
    0 3 val = 0
    0 4 val = 0
    1 0 val = 0
    1 1 val = 0
    1 2 val = 0
    1 3 val = 0
    1 4 val = 0
    2 0 val = 0
    2 1 val = 0
    2 2 val = 0
    2 3 val = 0
    2 4 val = 0


    Also Worth Noting for Indexing Purposes



    for rix in range(nrows):
    for cix in range(ncols):
    print l_of_ls[rix][cix],
    print


    RESULT



    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0





    share|improve this answer

































      1














      Showcasing the difference with memory layout:



      listOfLists = [] * 3
      listOfListsRange = [ for i in range(0, 3)]


      enter image description here






      share|improve this answer






























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        17














        []*2 is a list of two references to the same list. You are appending to it and then seeing it twice.






        share|improve this answer




























          17














          []*2 is a list of two references to the same list. You are appending to it and then seeing it twice.






          share|improve this answer


























            17












            17








            17







            []*2 is a list of two references to the same list. You are appending to it and then seeing it twice.






            share|improve this answer













            []*2 is a list of two references to the same list. You are appending to it and then seeing it twice.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 31 '11 at 10:01









            eumiroeumiro

            130k19230230




            130k19230230

























                12














                Because there is really only one list. Consider this:



                >>> l = []
                >>> l2 = l*2
                >>> l2[0] is l[0]
                True
                >>> l2[1] is l[0]
                True


                *2 performed on a list does not copy the list but return a list of length 2 filled with the same reference.



                What you probably wanted was this:



                >>> l = [ for _ in xrange(2)]


                As @Asterisk mentions in a comment, the same behaviour is exposed by all common collections. As a rule of thumb it is therefore best to only use multiplication on immutable types with value-semantics.






                share|improve this answer


























                • it seems *2 performed on dictionary does not copy as well...

                  – Asterisk
                  Aug 31 '11 at 10:13











                • and sets........

                  – Asterisk
                  Aug 31 '11 at 10:21
















                12














                Because there is really only one list. Consider this:



                >>> l = []
                >>> l2 = l*2
                >>> l2[0] is l[0]
                True
                >>> l2[1] is l[0]
                True


                *2 performed on a list does not copy the list but return a list of length 2 filled with the same reference.



                What you probably wanted was this:



                >>> l = [ for _ in xrange(2)]


                As @Asterisk mentions in a comment, the same behaviour is exposed by all common collections. As a rule of thumb it is therefore best to only use multiplication on immutable types with value-semantics.






                share|improve this answer


























                • it seems *2 performed on dictionary does not copy as well...

                  – Asterisk
                  Aug 31 '11 at 10:13











                • and sets........

                  – Asterisk
                  Aug 31 '11 at 10:21














                12












                12








                12







                Because there is really only one list. Consider this:



                >>> l = []
                >>> l2 = l*2
                >>> l2[0] is l[0]
                True
                >>> l2[1] is l[0]
                True


                *2 performed on a list does not copy the list but return a list of length 2 filled with the same reference.



                What you probably wanted was this:



                >>> l = [ for _ in xrange(2)]


                As @Asterisk mentions in a comment, the same behaviour is exposed by all common collections. As a rule of thumb it is therefore best to only use multiplication on immutable types with value-semantics.






                share|improve this answer















                Because there is really only one list. Consider this:



                >>> l = []
                >>> l2 = l*2
                >>> l2[0] is l[0]
                True
                >>> l2[1] is l[0]
                True


                *2 performed on a list does not copy the list but return a list of length 2 filled with the same reference.



                What you probably wanted was this:



                >>> l = [ for _ in xrange(2)]


                As @Asterisk mentions in a comment, the same behaviour is exposed by all common collections. As a rule of thumb it is therefore best to only use multiplication on immutable types with value-semantics.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 31 '11 at 10:25

























                answered Aug 31 '11 at 10:02









                blubbblubb

                5,76012756




                5,76012756













                • it seems *2 performed on dictionary does not copy as well...

                  – Asterisk
                  Aug 31 '11 at 10:13











                • and sets........

                  – Asterisk
                  Aug 31 '11 at 10:21



















                • it seems *2 performed on dictionary does not copy as well...

                  – Asterisk
                  Aug 31 '11 at 10:13











                • and sets........

                  – Asterisk
                  Aug 31 '11 at 10:21

















                it seems *2 performed on dictionary does not copy as well...

                – Asterisk
                Aug 31 '11 at 10:13





                it seems *2 performed on dictionary does not copy as well...

                – Asterisk
                Aug 31 '11 at 10:13













                and sets........

                – Asterisk
                Aug 31 '11 at 10:21





                and sets........

                – Asterisk
                Aug 31 '11 at 10:21











                1














                Here's how i initialize a list of lists. Rows vary slowest.



                nrows = 3; ncols = 5

                l_of_ls = [[0]*ncols for i in range(nrows )]

                for rix, r in enumerate(l_of_ls):
                for cix, c in enumerate(r):
                print rix, cix, 'val = ',c


                RESULT



                0 0 val =  0
                0 1 val = 0
                0 2 val = 0
                0 3 val = 0
                0 4 val = 0
                1 0 val = 0
                1 1 val = 0
                1 2 val = 0
                1 3 val = 0
                1 4 val = 0
                2 0 val = 0
                2 1 val = 0
                2 2 val = 0
                2 3 val = 0
                2 4 val = 0


                Also Worth Noting for Indexing Purposes



                for rix in range(nrows):
                for cix in range(ncols):
                print l_of_ls[rix][cix],
                print


                RESULT



                0 0 0 0 0
                0 0 0 0 0
                0 0 0 0 0





                share|improve this answer






























                  1














                  Here's how i initialize a list of lists. Rows vary slowest.



                  nrows = 3; ncols = 5

                  l_of_ls = [[0]*ncols for i in range(nrows )]

                  for rix, r in enumerate(l_of_ls):
                  for cix, c in enumerate(r):
                  print rix, cix, 'val = ',c


                  RESULT



                  0 0 val =  0
                  0 1 val = 0
                  0 2 val = 0
                  0 3 val = 0
                  0 4 val = 0
                  1 0 val = 0
                  1 1 val = 0
                  1 2 val = 0
                  1 3 val = 0
                  1 4 val = 0
                  2 0 val = 0
                  2 1 val = 0
                  2 2 val = 0
                  2 3 val = 0
                  2 4 val = 0


                  Also Worth Noting for Indexing Purposes



                  for rix in range(nrows):
                  for cix in range(ncols):
                  print l_of_ls[rix][cix],
                  print


                  RESULT



                  0 0 0 0 0
                  0 0 0 0 0
                  0 0 0 0 0





                  share|improve this answer




























                    1












                    1








                    1







                    Here's how i initialize a list of lists. Rows vary slowest.



                    nrows = 3; ncols = 5

                    l_of_ls = [[0]*ncols for i in range(nrows )]

                    for rix, r in enumerate(l_of_ls):
                    for cix, c in enumerate(r):
                    print rix, cix, 'val = ',c


                    RESULT



                    0 0 val =  0
                    0 1 val = 0
                    0 2 val = 0
                    0 3 val = 0
                    0 4 val = 0
                    1 0 val = 0
                    1 1 val = 0
                    1 2 val = 0
                    1 3 val = 0
                    1 4 val = 0
                    2 0 val = 0
                    2 1 val = 0
                    2 2 val = 0
                    2 3 val = 0
                    2 4 val = 0


                    Also Worth Noting for Indexing Purposes



                    for rix in range(nrows):
                    for cix in range(ncols):
                    print l_of_ls[rix][cix],
                    print


                    RESULT



                    0 0 0 0 0
                    0 0 0 0 0
                    0 0 0 0 0





                    share|improve this answer















                    Here's how i initialize a list of lists. Rows vary slowest.



                    nrows = 3; ncols = 5

                    l_of_ls = [[0]*ncols for i in range(nrows )]

                    for rix, r in enumerate(l_of_ls):
                    for cix, c in enumerate(r):
                    print rix, cix, 'val = ',c


                    RESULT



                    0 0 val =  0
                    0 1 val = 0
                    0 2 val = 0
                    0 3 val = 0
                    0 4 val = 0
                    1 0 val = 0
                    1 1 val = 0
                    1 2 val = 0
                    1 3 val = 0
                    1 4 val = 0
                    2 0 val = 0
                    2 1 val = 0
                    2 2 val = 0
                    2 3 val = 0
                    2 4 val = 0


                    Also Worth Noting for Indexing Purposes



                    for rix in range(nrows):
                    for cix in range(ncols):
                    print l_of_ls[rix][cix],
                    print


                    RESULT



                    0 0 0 0 0
                    0 0 0 0 0
                    0 0 0 0 0






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 25 '15 at 19:30

























                    answered Apr 25 '15 at 19:10









                    Love and peace - Joe CodeswellLove and peace - Joe Codeswell

                    1,49112035




                    1,49112035























                        1














                        Showcasing the difference with memory layout:



                        listOfLists = [] * 3
                        listOfListsRange = [ for i in range(0, 3)]


                        enter image description here






                        share|improve this answer




























                          1














                          Showcasing the difference with memory layout:



                          listOfLists = [] * 3
                          listOfListsRange = [ for i in range(0, 3)]


                          enter image description here






                          share|improve this answer


























                            1












                            1








                            1







                            Showcasing the difference with memory layout:



                            listOfLists = [] * 3
                            listOfListsRange = [ for i in range(0, 3)]


                            enter image description here






                            share|improve this answer













                            Showcasing the difference with memory layout:



                            listOfLists = [] * 3
                            listOfListsRange = [ for i in range(0, 3)]


                            enter image description here







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 6 '17 at 22:11









                            user1767754user1767754

                            9,98457184




                            9,98457184















                                Popular posts from this blog

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues