I have a list which contains first and last names, like this one:
names = ["John Smith", "Rob Julian", "Eric Walls"]
I want to get only the first names in this list.
I achieved that by doing:
first_names = [n.split(" ")[0] for n in names]
And that gave me the wanted result.
But in my opinion this is pretty ugly, is there any better way to achieve that goal?
Yes, but not really. Performance wise you are better off with what you have.
would work, but i love list comprehension in python. I mean whats wrong with
For fun, you could also do the following. I would imagine if you are processing a very large list this might have the best performance. But, you might want to investigate that first.
to make this comprehensive, you could also use the lambda to map it.
Per comments, I am adding yet another way
in conclusion, yes there are other ways to do it.
but your original seems to be the most preferred. If speed is an issue you may want to tinker with the others.
updated with time
not the most scientific, but using a list of approximaltey 3.5million names, I ran the above calling the files n0-4 and ran
time n0;time n1; time n2; time n3; time n4here are my results. Looks as if the original list comprehension was the fastest on my machine.
(I ran them a few times in differing orders, times were consistent.)