0

Why does index assignment of another list form a linked list and list slice(one element slice) assignment of another list makes the list part of the original list when both the slice and element with the index points the same element? What changes happen in the memory allocation?

l = [1,2,3,4,5,6]
l[2:3] = [7,8]  # gives [1,2,7,8,5,6]

# whereas:

l[2] = [7,8]  # gives [1,2,[7,8],4,5,6]

and initialy l[2]=3 and l[2:3]=3

7
  • 1
    Your English is incomprehensible. Commented Sep 2, 2016 at 17:37
  • Provide an example to explain your question. Commented Sep 2, 2016 at 18:11
  • Assume l is list l=[1,2,3,4,5,6] Commented Sep 2, 2016 at 18:28
  • l[2:3]=[7,8] gives [1,2,7,8,5,6] Commented Sep 2, 2016 at 18:31
  • whereas l[2]=[7,8] gives [1,2,[7,8],4,5,6] and initialy l[2]=3 and l[2:3]=3 Commented Sep 2, 2016 at 18:33

1 Answer 1

1

Your assumption is incorrect, when you say "initialy l[2]=3 and l[2:3]=3".

This is how it is, in fact:

l = [1, 2, 3, 4, 5, 6]

l[2]  # 3

l[2:3]  # [3]

l[2] is the element at index 2. l[2:3] is the slice (a sublist) of length one starting at index 2.

Therefore, assigning to l[2] change to element and assigning to l[2:3] replaces a slice with another slice, exactly as you noticed:

l = [1, 2, 3, 4, 5, 6]
l[2:3] = [7,8]  # l is now [1, 2, 7, 8, 4, 5, 6]

l = [1, 2, 3, 4, 5, 6]
l[2] = [7,8]  # l is now [1, 2, [7, 8], 4, 5, 6]
Sign up to request clarification or add additional context in comments.

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.