'Difference between a[1] and a[1:1] in lists [duplicate]

If we have a list a = [1,2,3,4] and list b = [5,6,7]

why is a[1] interpreted differently than a[1:1] and what exactly is the difference?

If I want to add all of list b to list a at index 1, so that the list a becomes [1,5,6,7,2,3,4] why do I have to run a[1:1] = b instead of a[1] = b?

how exactly is a[1:1] interpreted?



Solution 1:[1]

a[1:1] means an empty slice spanning from before index 1, and until before index 1. It does not include 1, as that would be a[1:2].

When you replace that empty slice, you basically insert the new list in that position.

If you do a[1] you replace the item at position 1 with the list.

Some examples:

>>> a = [1,2,3]
>>> b = [4,4,4,4]
>>> a[1] = b
>>> a
[1, [4, 4, 4, 4], 3]    # [4, 4, 4, 4] is a sublist
>>> a[1]
[4, 4, 4, 4]
>>> len(a)
3  # List contains only 3 items - `1`, the sublist, and `3`.
>>> a = [1,2,3] # Reset back
>>> a[1:1] = b
>>> a
[1, 4, 4, 4, 4, 2, 3]
>>> len(a)
7  # List contains 7 integers

Solution 2:[2]

a[1] is for get single value from list by index in square brackets (0 is first value) and a[1:1] is for get subset of list, not only one value. ([start:end]), but in this case get empty list, because start and end it's same

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 zbyso