2

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!

3 Answers 3

4
>>> 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I see, I was thinking that 0:3 was the first FOUR elements, I didn't realize that the 3 wasn't included. Thank you for the clear answer, I'll accept it soon!
Yep, timer just ran down. Thank you to everyone that cleared that up!
2

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.