2

I know the difference in a[:] and a in assignment to a variable and also the special case of slice assignment.

Suppose,

a=[1,2,3,4,5]  

What is the difference between the following two statements?

b=a[:]+[6,7,8,9,10] #1   
b=a+[6,7,8,9,10] #2  

In both cases, both a and b have the same values at the end.

I have referred the following links -

When and why to use [:] in python

Understanding slice notation

Python why would you use [:] over =

They haven't mentioned their difference in an expression as such.

DoubtExpert
  • 71
  • 1
  • 10
  • `[:]` select all the values of the list, it's a slicing character in python list, however, if there is a number after `:` it slice either from that index or to that index depending on the position before or after the `:`. – arajshree Jun 27 '19 at 06:59
  • 2
    the first statement makes a (unnecessary) copy of `a` first. the second one does not. – hiro protagonist Jun 27 '19 at 07:00

3 Answers3

5

a[:] grabs a full slice of the list – in this context, it has no difference in effect since you're assigning to a new list (though it does copy the list, so it's slower at scale).

# create the list.
>>> a = [1, 2, 3, 4, 5]
# see its address
>>> id(a)
4349194440
# see the (different) address of a copy
>>> id(a[:])
4350338120
# reassign the entire list using slice syntax
>>> a[:] = [5, 6, 7]
>>> a
[5, 6, 7]
# still the same first ID though
>>> id(a)
4349194440
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172
0

In python list slicing a[:] and a has only difference in their id's because a[:] is making an exact copy of a in another address location.

Also considering python immutable string slicing a[:] and a have no difference.Both points to same address location.

Arun Augustine
  • 1,690
  • 1
  • 13
  • 20
0
a=[1,2,3,4,5] 
b=a[:]+[6,7,8,9,10] #1  
b=a+[6,7,8,9,10] #2 

Case-1 a[:] , means you are slicing the sequence and a sequence can be anything like string, list etc. Basically this is read as a[start:end:steps],where start end are our indexing values AND steps are number of jumps. If we do not provide any values then by default start = 0 AND end = last element of sequence AND steps = 1. So in your case, you are simply taking the whole elements of list a.

Case-2 a , It simply means the whole a

Conclusion:- With the help of a[:] you can get the desired elements.

Examples-->>

a = [1,2,3,4]
a[1:4]
>> [1,2,3]
a[::2]
>> [1,3]

I hope it may help you.

Rahul charan
  • 765
  • 7
  • 15