Chase
Chase

Reputation: 161

(Python) Behaviour Of The Slice Function Within A List

I'm learning Python and have a basic grasp of the way Slice works, but there's a particular block of code that I'm having trouble grasping:

L = [2,4,6,8,0]

L[0:3] = [2,4,6,8]

print L[4]

The output of this is 8, which I find strange; I'd expect it to still be 0 as I read the second line as "transform the first 4 elements of the list into 2,4,6,8." This would still leave a list of [2,4,6,8,0], which is obviously not happening. I'd be grateful if anyone could explain why Slice is behaving this way!

Upvotes: 2

Views: 54

Answers (3)

George
George

Reputation: 109

You should be doing

L = [2,4,6,8,0]
L[0:4] = [2,4,6,8]
print L[4]

to get 0

Because if

L = [2,4,6,8,0]
L[0:3] 

refers to

[2,4,6]

and

L[0:4] 

refers to

[2,4,6,8]

So in your example i think you want L[0:4] so that you can transform them into the new values

Upvotes: 0

McGrady
McGrady

Reputation: 11477

>>> L = [2,4,6,8,0]
>>> L[0:3] = [2,4,6,8]
>>> L
[2, 4, 6, 8, 8, 0]

This changes the list,L[0:3] is [2, 4, 6],so you append another 8 after 6,that's why the forth value is 8 now:

>>> L[4]
8

Have a look at this picture:

enter image description here

So maybe what you want is L[0:4] or L[:4].Hope this helps.

Upvotes: 4

user6165050
user6165050

Reputation:

The output is 8 because when you're doing:

L[0:3] = [2,4,6,8]

You're adding an extra 8 at the end of the list [2,4,6,8]:

L[0:3] = [2,4,6,8]
print(L)

The length of L[0:3] is 3, and you're assigning 4 values to it. That's why this is happening.

Output:

[2, 4, 6, 8, 8, 0]

As you can see, L[4] is now 8

Upvotes: 2

Related Questions