List assignment with [:]

后端 未结 6 1052
小蘑菇
小蘑菇 2020-11-29 09:42

What\'s the difference between

list = range(100)

and

list[:] = range(100)

in Python?

EDI

6条回答
  •  失恋的感觉
    2020-11-29 10:15

    [:] is also useful to make a deep copy of the list.

    def x(l):
        f=l[:]
        g=l
        l.append(8)
        print "l", l
        print "g", g
        print "f", f
    
    l = range(3)
    
    print l
     #[0, 1, 2]
    
    x(l)
     #l [0, 1, 2, 8]
     #g [0, 1, 2, 8]
     #f [0, 1, 2]
    
    print l
    #[0, 1, 2, 8]
    

    Modification to l is get reflected in g (because, both point to same list, in fact, both g and l are just names in python), not in f(because, it's a copy of l)

    But, in your case, It doesn't make any difference. (Though, I'm not eligible to comment on any memory usage of both methods.)

    Edit

    h = range(3)
    id(h) #141312204 
    h[:]=range(3)
    id(h) #141312204 
    h=range(3)
    id(h) #141312588 
    

    list[:] = range(100) updates the list list = range(100) creates new list.

    @agf: thanks for pointing my error

提交回复
热议问题