Bob
Bob

Reputation: 115

How to create an if statement for elements within a list?

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

Answers (3)

Dito Khelaia
Dito Khelaia

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

KuboMD
KuboMD

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

okovko
okovko

Reputation: 1911

The most succinct way to do this in Python 3 is to use a generator expression:

if any(5 < x < 10 for x in lst):
  lst.append('***')

Here is a working example.

Edit: That syntax is kind of mind blowing, thanks for the edit and the comment.

Upvotes: 2

Related Questions