Reputation: 171
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
Python why would you use [:] over =
They haven't mentioned their difference in an expression as such.
Upvotes: 2
Views: 232
Reputation: 837
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.
Upvotes: 0
Reputation: 1766
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.
Upvotes: 0
Reputation: 168913
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
>>>
Upvotes: 5