Juan
Juan

Reputation: 2103

Slices index python

Why when I run

>>> lista = [1,2,3,4,5]
>>> newl = [8,10]
>>> lista[1:4] = newl
[1,8,10,5]

The indexes for replaced values are between 1 until 3. And when I run.

>>> lista[2:2] = newl
[1,2,8,10,3,4,5]

A new index is created to save newl.

Upvotes: 0

Views: 70

Answers (3)

gboffi
gboffi

Reputation: 25033

In the first case you tell python to replace 3 specific elements in lista with other 2 elements from newl.

In the second case you reinitialize lista, then you select for substitution lista[2:2] that is an empty list ([]), and more precisely the empty list before the 3rd element of the list (whose index is 2) and so you replace this empty list with the two values from newl.

Upvotes: 1

user2961646
user2961646

Reputation:

Index

To understand slicing, you need to understand this.

Let's say

hi = "Hello"

The slice hi[1:2] contains "e". It starts at the second character and ends before the third. hi[2:2] contains nothing, because it starts at the third character and ends before the third character.

If you are inserting something between characters, it is replacing it. If you do:

hi[1:3] = "abcd"

Then "abcd" is replacing "el". This is the same with lists.

Upvotes: 1

khelwood
khelwood

Reputation: 59111

Slice indexes are start-inclusive and end-exclusive.

mylist[1:4] contains the elements at indexes 1, 2, and 3.

From http://docs.python.org/2/library/stdtypes.html:

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j.

So if you get mylist[2:2] you are retrieving elements for which 2 <= k < 2 (no elements).

However, the list slicing syntax is clever enough to let you assign into that space, and insert elements into that position. If you run

mylist[2:2] = [5,6,7]

then you are inserting element into that space before index 2 that currently holds no elements.

Upvotes: 1

Related Questions