-1

I have this list

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

I would like to convert elements greater than 3 as 0 so the list would become [1,2,3,0,0,0]

Here is my code

for i in range(len(x)): 
  if x[i] > 3:
    x = 0

I got this error message " 'int' object is not subscriptable". could somebody tell me what I did wrong

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
VTD
  • 67
  • 4
  • 3
    `could somebody tell me what I did wrong`: Look at your code and think about what `x = 0` does. – Selcuk Aug 23 '21 at 03:12
  • 3
    After the first instance that `x > 3` you set the `list` `x = 0` from that point forward it is a _number_. You probably meant `x[i] = 0` – Henry Ecker Aug 23 '21 at 03:13

1 Answers1

2

Problem with your current code is, you are assigning 0 directly to x, not to the item at a particular index, the same way you are comparing the value.

for i in range(len(x)): 
  if x[i] > 3:
    # x = 0
    x[i] = 0  #<---- assign value at the index i

Or, you can just use a list-comprehension, and take 0 if the value is greater than 3, else take the value

>>> [0 if i>3 else i for i in x]
[1, 2, 3, 0, 0, 0]
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45