Reputation: 115
I am wondering how I can create an if statement that does something to a list as long as there is at least one value in the list that meets the if statement's requirements.
For example, given a list
x=[1,2,3,4,5,6,7,8,9]
y=[1,2,3,4]
z=[1,2,3,8]
I want to create an if statement where if the list contains elements whose values are between 5 and 10, then the list appends ***.
Meaning, after the if statement, the results would be
x=[1,2,3,4,5,6,7,8,9,***]
y=[1,2,3,4]
z=[1,2,3,8,***]
since both x and z contains elements that are between 5 and 10, they receive the ***.
Upvotes: 1
Views: 2263
Reputation: 138
i=0
while i<len(x):
if x[i]>5 and x[i]<10: #if any item of list is between 5 and 10 break loop
break
i+=1
if i<len(x): #check if i less than len(x) this means that loop 'broken' until the end
x.append('***')
Upvotes: -1
Reputation: 684
You could do this. Test if any of the elements match your condition using a generator expression and the any()
function.
x = [1,2,3,4] #two lists for testing
y = [5]
if any(5 <= i <= 10 for i in x):
x.append("***")
if any(5 <= i <= 10 for i in y):
y.append("***")
print(x,y)
Output:
[1, 2, 3, 4] [5, '***']
Upvotes: 4