-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

2
  • 3
    could somebody tell me what I did wrong: Look at your code and think about what x = 0 does. Commented Aug 23, 2021 at 3: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 Commented Aug 23, 2021 at 3:13

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.