0

I have a list of elements in Python and need to assign a number to the entire list. In R, I could simply do the assignment and R would rep that number the necessary number of times. In Python, is the easiest thing to do a list comprehension?

x = [1,2,3,4,5]
#want to assign 0 to every element, would like to do x[:] = 0 but this causes an error
x[:] = [0 for i in range(len(x))] #pretty long for such a simple operation
Alex
  • 18,593
  • 36
  • 118
  • 187

3 Answers3

2

Yes, a comprehension such as [0 for _ in x] is the way to go (no need for range(len(... if you're not doing anything with the values). R's syntax places heavy emphasis on vectors, while Python has a preference for explicit instructions in this sort of case.

TigerhawkT3
  • 46,954
  • 6
  • 53
  • 87
1

You could also try:

x = [1,2,3,4,5]
x = [0] * len(x)

Hope this helps.

station
  • 6,169
  • 11
  • 51
  • 86
1
>>> x[:] = [0]*len(x)
>>> x
[0, 0, 0, 0, 0]
mechanical_meat
  • 155,494
  • 24
  • 217
  • 209