Reputation: 13
>>> aa = [10, 20, 30]
>>> aa[1:2] = 100, 200
[10, 100, 200, 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = [100, 200]
[10, 100, 200, 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = (100, 200)
[10, 100, 200, 30]
I'm a beginner to Python. I tried to change 20
into 100, 200
, so I tried 3 ways of inserting these 2 numbers: ints, a list, and a tuple. Why is the result the same when I insert ints or a list or a tuple in aa[1:2]?
Upvotes: 1
Views: 29
Reputation: 3973
By using aa[1:2]
, you are modifying a list item using slice assignment. Slice assignment replaces the specified item (or items), in this case the second item in aa
, with whatever new item(s) that is specified. I'll go through each type to clarify what is happening
Ints - aa[1:2] = 100, 200
: this example is the most clear. We are replacing aa[1:2]
with two ints that go into the list in that spot.
List/Tuple: this example of how slice assignment works -- instead of adding a list to the list, it extends the new list into the old list. The tuple works the same way. To replace the item and add a list or tuple, wrap the list or tuple in another list first:
>>> aa = [10, 20, 30]
>>> aa[1:2] = [[100, 200]]
[10, [100, 200], 30]
>>> aa = [10, 20, 30]
>>> aa[1:2] = [(100, 200)]
[10, (100, 200), 30]
Upvotes: 1