1

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 ***.

asked Jan 18, 2019 at 19:52
4
  • 1
    What is ***?? Commented Jan 18, 2019 at 19:53
  • 1
    Perhaps this will help: stackoverflow.com/q/19389490/4996248 Commented Jan 18, 2019 at 19:55
  • 3
    This sounds like homework. At the very least you should show us what you have tried Commented Jan 18, 2019 at 19:55
  • 1
    You should loop over the list (or use a list comprehension) to verify that the condition is satisfied and in case do what you want to do. Commented Jan 18, 2019 at 19:55

3 Answers 3

4

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, '***']
John Kugelman
365k70 gold badges555 silver badges600 bronze badges
answered Jan 18, 2019 at 19:58
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Jan 18, 2019 at 19:58

Comments

-1
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('***')
answered Jan 18, 2019 at 19:58

1 Comment

You should try to do this without while, iterator and break. Your code is too complex. Do not forget the Zen of python and Keep It Simple Stupid (KISS).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.