Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all elements in a list by a single variable

nums = [1,2,3,4,5,6]
replace = 1

for x in nums:
    x = replace
    print(x)

How can I replace all nums to 1:

nums = [1,1,1,1,1,1]

like image 580
Sun Avatar asked May 18 '26 19:05

Sun


1 Answers

If the number (in this case, 1) is known, just re-assign it like this:

replace = 1
nums = [replace]*len(nums)

This is way much faster than iteration as suggested in other answers in case of too many numbers.

>>> start=time.time(); a = [1 for _ in range(1000000)]; print(time.time() - start)
0.039171695709228516
>>> start=time.time(); a = [1] * 1000000; print(time.time() - start)
0.0036449432373046875
like image 95
Jarvis Avatar answered May 20 '26 07:05

Jarvis