2
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]

quamrana
  • 33,740
  • 12
  • 54
  • 68
Sun
  • 25
  • 4

6 Answers6

3

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
Jarvis
  • 8,331
  • 3
  • 26
  • 54
  • 2
    Don't use this for nested lists tho https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly :-) – U12-Forward Dec 26 '20 at 11:08
2

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]  
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
2

Try this:

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

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]
IoaTzimas
  • 10,263
  • 2
  • 10
  • 29
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
quamrana
  • 33,740
  • 12
  • 54
  • 68
1

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)