Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign one value to the entire (or partial) list in Python?

I have List = [0, 1, 2, 3] and I want to assign all of them a number say, 5: List = [5, 5, 5, 5]. I know I can do List = [5] * 4 easily. But I also want to be able to assign say, 6 to the last 3 elements.

List = [5, 5, 5, 5]

YourAnswer(List, 6, 1, 3)

>> [5, 6, 6, 6]

How can such a YourAnswer function be implemented, preferably without a for loop?

like image 914
elwc Avatar asked Jan 29 '26 19:01

elwc


2 Answers

You can actually use the slice assignment mechanism to assign to part of the list.

>>> some_list = [0, 1, 2, 3]
>>> some_list[:1] = [5]*1
>>> some_list[1:] = [6]*3
>>> some_list
[5, 6, 6, 6]

This is beneficial if you are updating the same list, but in case you want to create a new list, you can simply create a new list based on your criteria by concatenation

>>> [5]*1 + [6]*3
[5, 6, 6, 6]

You can wrap it over to a function

>>> def YourAnswer(lst, repl, index, size):
    lst[index:index + size] = [repl] * size


>>> some_list = [0, 1, 2, 3]
>>> YourAnswer(some_list, 6, 1, 3)
>>> some_list
[0, 6, 6, 6]
like image 125
Abhijit Avatar answered Feb 01 '26 14:02

Abhijit


In [138]: def func(lis,x,y,z):
   .....:     return lis[:y]+[x]*z
   .....: 

In [139]: lis=[5,5,5,5]

In [140]: func(lis,6,1,3)
Out[140]: [5, 6, 6, 6]
like image 41
Ashwini Chaudhary Avatar answered Feb 01 '26 13:02

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!