hellriser
hellriser

Reputation: 27

how to incorporate 'if' condition into for loop statement

data = [(1,'hi'),(2,'hello'),(3,'hi'),(4,'hi'),(5,'hello'),(6,'hello'), 
(7,'hi'),(8,'hello')]
new_data = []
for i in data:
    if i[1] == 'hi':
        new_data.append(i)
print(new_data)

output:[(1, 'hi'), (3, 'hi'), (4, 'hi'), (7, 'hi')]

i am a beginner in python. i want the same output but want to reduce the amount of code in the'For' loop and be more efficient.

Upvotes: 0

Views: 91

Answers (2)

Pieter De Clercq
Pieter De Clercq

Reputation: 1961

You can use a list comprehension and a filter to write in on one line. There is a good explanation on filters available at this question. Using filters you can make use of lazy evaluation, which benefits the execution time.

data = [(1,'hi'),(2,'hello'),(3,'hi'),(4,'hi'),(5,'hello'),(6,'hello'), (7,'hi'),(8,'hello')]
new_data = list(filter(lambda i: i[1] == 'hi', data))

Output

[(1, 'hi'), (3, 'hi'), (4, 'hi'), (7, 'hi')]

Upvotes: 0

user2390182
user2390182

Reputation: 73450

While your loop is fine, you can use a list comprehension:

new_data = [i for i in data if i[1] == 'hi']

Upvotes: 1

Related Questions