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.

asked Sep 4, 2018 at 8:58
2
  • 1
    Your code is easy to understand, and does exactly what it should do. The few extra lines shouldn't matter too much. Commented Sep 4, 2018 at 9:00
  • 3
    new_data = [x for x in data if x[1]=='hi'] Commented Sep 4, 2018 at 9:00

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

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')]
answered Sep 4, 2018 at 9:05

Comments

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.