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.
2 Answers 2
While your loop is fine, you can use a list comprehension:
new_data = [i for i in data if i[1] == 'hi']
answered Sep 4, 2018 at 9:00
user2390182
73.7k6 gold badges71 silver badges95 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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')]
answered Sep 4, 2018 at 9:05
Pieter De Clercq
1,9711 gold badge17 silver badges29 bronze badges
Comments
lang-py
new_data = [x for x in data if x[1]=='hi']