How i can make number from the list is less than 18, then the number is not printed?

Question:

#Code
x = [17, 15, 18, 21, 5, 6]
   for y in x:
        if y < 18:
            y = x.copy()
            print (y)

In answer python:[17, 15, 18, 21, 5, 6], [17, 15, 18, 21, 5, 6], [17, 15, 18, 21, 5, 6], [17, 15, 18, 21, 5, 6], [17, 15, 18, 21, 5, 6]

Asked By: JK Lite

||

Answers:

Iterate over the values, if the value is valid (>=18) keep it in an other list, at the end print them

x = [17, 15, 18, 21, 5, 6]
valid_values = []
for y in x:
    if y >= 18:
        valid_values.append(y)
print(valid_values)  # [18, 21]

With list-comprehension

valid_values = [y for y in x if y >= 18]
Answered By: azro

You can do this by building a new list and printing the result:

x = [17, 15, 18, 21, 5, 6]
print(*[v for v in x if v >= 18])

Output:

18 21
Answered By: Cobra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.