简体   繁体   中英

Python : why results are same when i put int or list or tuple in list?

>>> 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]?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM