How does it work for the list [1:]?



  • If my code looks like:

    l = [1, 2, 3, 4]
    

    s = l[1:]

    To s - it's still a reference. lwhich reads it by the rule [1:]or a new list has been established l = [2, 3, 4]the value of which s?



  • It's actually an interesting and difficult question. When you create a cut, Python creates copies. References on the elements of the list:

    In [58]: l = [1000, 2000, 3000, 4000]
    

    In [59]: s = l[1:]

    In [60]: [id(x) for x in l]
    Out[60]: [140412420854224, 140412420857168, 140412420854032, 140412420857648]

    In [61]: [id(x) for x in s]
    Out[61]: [140412420857168, 140412420854032, 140412420857648]

    At first glance, it may appear that s - that reference l[1:], but if you change one of the s - it won't change the original data. l:

    In [62]: s[0] += 111

    In [63]: s
    Out[63]: [2111, 3000, 4000]

    In [64]: l
    Out[64]: [1000, 2000, 3000, 4000]


    If you dig deeper and use the list of lists, the situation will change dramatically, draw attention to the modified element in the reference list. llafter we changed the element in the subscription. ss:

    In [65]: ll = [[1000, 1000], [2000, 2000]]

    In [66]: ss = ll[1:]

    In [67]: ss[0][0] += 111

    In [68]: ll
    Out[68]: [[1000, 1000], [2111, 2000]]

    In [69]: ss
    Out[69]: [[2111, 2000]]

    but... id still match:

    In [70]: [id(x) for x in ll]
    Out[70]: [140411607786432, 140413521522240]

    In [71]: [id(x) for x in ss]
    Out[71]: [140413521522240]



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2