ValueError: attempt to assign sequence of size 6 to extended slice of size 5

 Lets understand the following program:

mylist = [1,2,3,4,5,6,7,8,9,10] # length of the list is 10
mylist[::2] = ['a','b','c','d','e','f'] # sliced the list with step count 2 and trying to assign 6 elements.
print(mylist)


Error
: ValueError: attempt to assign sequence of size 6 to extended slice of size 5

Want to know why the above error is occurred?

In the above program, the list mylist's size is 10. The extended slice's step count is 2 and it's length is 5. Our program will throw an error if we are trying to assign more than 5 elements.

Lets fix this program,

mylist = [1,2,3,4,5,6,7,8,9,10] 

mylist[::2] = ['a','b','c','d','e']

print(mylist)
output : ['a', 2, 'b', 4, 'c', 6, 'd', 8, 'e', 10]

I hope you understand. 


No comments:

Post a Comment

Pages