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
  • 37,849
  • 12
  • 53
  • 71
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,494
  • 3
  • 27
  • 58
  • 2
    Don't use this for nested lists tho https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly :-) – U13-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]  
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

Try this:

nums = [1,2,3,4,5,6]
replace=1
nums=[replace]*len(nums)
Walid
  • 718
  • 5
  • 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,538
  • 2
  • 13
  • 30
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
  • 37,849
  • 12
  • 53
  • 71
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)
ketan gangal
  • 33
  • 1
  • 8