Reputation: 37
So my input file f
is like
5 100
2 200
8 300
My output is a list of tuples:
[(5, 100), (2, 200), (8, 300)]
My code is as below.
f = open(file_name, "r")
lines = f.readlines()
sets= []
for line in lines:
a, b= line.split(' ')
sets.append((int(a), int(b)))
Is it possible to convert the for loop to a list comprehension? Also someone told me a list comprehension is faster to run in most cases. Is it the case? And is it always a good practice to convert iterative operations to a shorter list comprehension when possible?
Upvotes: 0
Views: 128
Reputation: 7509
with open(file_name, "r") as f:
sets = [tuple(map(int, line.split(" "))) for line in f]
Regarding your other questions: comprehensions are often faster, yes, but not always significantly so, and it's hard to comment in the abstract without a concrete use case.
Your second question is more opinionated, and again, varies with each use case. For relatively simple operations like this one, I find a list comprehension to be more readable and to-the-point than a for-loop (though I tend to try to avoid nested comprehensions where possible — notice I used map
rather than a nested-comprehension in my answer — it's just personal preference, really). Moreover, not everything that can be written as a for-loop can be rewritten as a comprehension, and not everything that can be written as a comprehension necessarily should be written as a comprehension. For more complex operations, it can often make it really unreadable to cram it into one comprehension, so in those cases you're almost certainly better off sticking with a for-loop.
Upvotes: 4