for loop that replaces element based on its value

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



for loop that replaces element based on its value



I have a list of integers and I am trying to define a function which loops through every element to check if they are less than 5 and returns the list in string according to their contents.


intlist=[12, 10, 11, 23, 25, 2]

def clear(x):
for i in x:
if i < 5:
x[i] = 0
return str(x)
else:
return str(x)

print clear(intlist)



My code is not working as intended, could anyone enlighten me?



If they are, I am to change all elements in the list to '0'. The outcome should look something like this.


intlist=[0, 0, 0, 0, 0, 0]



However if none of the elements are less than 5, the output should remain the same.


intlist=[12, 10, 11, 23, 25, 2]





What's the error message? As I can see in your code your indentations are not valid for if-else block.
– Akshay Nevrekar
8 mins ago


if-else





In condition, there should be if x[i]<5 instead of i<5...
– Sapan Zaveri
6 mins ago





4 Answers
4



Welcome to StackOverflow! Your code has some logic problem. Here's my fix:


intlist=[12, 10, 11, 23, 25, 2]

def clear(x):
for i in x:
if i < 5: # If this is satisfied once, return string with n times of '0'
x = [0]*len(x) # This creates a list of zeros with same length as before
return str(x)

print clear(intlist)



Besides, in your example the element 2 is less than 5, so the output should be 000000


2


000000





thank you! this works but I would like to ask if an else statement is possible here?
– Samuel Tan
3 mins ago





@SamuelTan yeah it is possible but not necessary.
– Kevin Fang
3 mins ago



You can do it one one-line, creating a list of zeros if any one of the elements in list is less than 5 or retaining the list otherwise.


5


intlist = [12, 10, 11, 23, 25, 2]

intlist = [0] * len(intlist) if any(x for x in intlist if x < 5) else intlist

print(intlist)
# [0, 0, 0, 0, 0, 0]


intlist=[12, 10, 11, 23, 25, 2]

def clear(x):
if (any(i<5 for i in intlist)): return [0]*len(intlist)
else: return(x)
print(clear(intlist)) # [0, 0, 0, 0, 0, 0]



check for the any item is <5 then return all zeros or keep the list as it is.



Try this out if you want to use function as well as an if-else block :


intlist=[12, 10, 11, 23, 25, 2]

def clear(x):
for i in range(len(x)):
if x[i]<5 :
x[i] = 0
else:
continue
return x

print(clear(intlist)) # Python 3
print clear(intlist) # Python 2






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard