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

Viewed 68
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]

6 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

x=replace replaces the iterator, not the value in the list, so try using list comprehension:

nums = [replace for x in nums]
print(nums)

Output:

[1, 1, 1, 1, 1, 1]  

Try this:

nums = [1,2,3,4,5,6]
replace=1
nums=[replace]*len(nums)

If you want to use a loop, you can do the following:

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

replace=1

for i in range(len(nums)):
    nums[i]=replace

>>> print(nums)

[1, 1, 1, 1, 1, 1]

There are several ways apart from nums=[1,1,1,1,1,1]:

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

for index,_ in enumerate(nums):
    nums[index] = replace

let me know if you have other questions.

First Mtd:-

nums = [1,2,3,4,5,6]
replace = 1
nums = list(map(lambda x : replace,nums))

second Mtd:-

nums = [1,2,3,4,5,6]
replace = 1
nums = [replace for i in range(len(nums))] 
print(nums)
Related