-2
>>> ex=[1,2,3,4,5,6,7,8]
>>> ex
[1, 2, 3, 4, 5, 6, 7, 8]
>>> ex[1:4]=[99,88,77]
>>> ex
[1, 99, 88, 77, 5, 6, 7, 8]
>>> ex[1:1]=['s','t','u']
>>> ex
[1, 's', 't', 'u', 99, 88, 77, 5, 6, 7, 8]

Why ex[1:4] and ex[1:1] gives same output? what is the use of second value in ex[1:1]?

user1762571
  • 1,888
  • 7
  • 28
  • 47

3 Answers3

3

They don't give the same value. In the first the elements are replaced by 99, 88, 77 whereas in the second one, the list is increased to accomodate s, t, u.

The Python's Slice notation has been explained in this question.

ex[1:4]=[99,88,77] replaces the slice of ex with the contents 99, 88, 77. While, ex[1:1]=['s', 't', 'u'] inserts s, t, u into the list.

Community
  • 1
  • 1
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
2

By doing ex[1:1], you're putting your "insert" starting before index 1 instead of replacing index 1.

ex = [1,2,3,4,5,6,7]
ex[1:1] = 3
print ex

yields:

[1,3,2,3,4,5,6,7]
sihrc
  • 2,728
  • 2
  • 22
  • 43
1

lst[start:end] = some_seq means that replace the slice starting at start and ending at end - 1 with the sequence on the RHS.

lst[n:n] = sequence means that insert the sequence on the RHS at the index n in the list.

Not really same I would say.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71