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

hellriser
  • 27
  • 4

2 Answers2

1

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

new_data = [i for i in data if i[1] == 'hi']
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

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')]
Pieter De Clercq
  • 1,951
  • 1
  • 17
  • 29