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
  • 19,533
  • 37
  • 126
  • 195

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
  • 48,464
  • 6
  • 60
  • 97
1

You could also try:

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

Hope this helps.

station
  • 6,715
  • 14
  • 55
  • 89
1
>>> x[:] = [0]*len(x)
>>> x
[0, 0, 0, 0, 0]
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223