1

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?

S.B
  • 13,077
  • 10
  • 22
  • 49
Sam
  • 21
  • 2
  • 2
    The difference is replacing a single element of list `a` with list `b` (making it nested) as opposed to replacing an (empty) sublist of `a` with `b`. – tobias_k Jan 26 '22 at 14:51
  • I think this is a timely question. The behaviour is unexpected imo and doesn't feel very pythonic, but afaik it is the simplest way to insert (and unpack) a list into another list. The explanations below are as good as they will get, unfortunately. – edvard Jan 26 '22 at 15:01

2 Answers2

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
Bharel
  • 23,672
  • 5
  • 40
  • 80
0

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

zbyso
  • 108
  • 5