Reputation: 141
I've got a list of full names from a csv file, but I only want to apply my next piece of code to the first names from that list. The list looks like this:
['michelle rodriguez', 'dexter king', 'gurukavari']
But then for a few thousand names. As you can see, some of the names don't contain a last name, and some do. How do I create a new list which contains only the first names from this list?
Upvotes: 1
Views: 17044
Reputation: 13586
name = "Saurabh Chandra Patel"
first_name = name.rsplit(' ', 1)[0]
last_name = name.rsplit(' ', 1)[1]
if name = "Saurabh Patel"
Upvotes: 0
Reputation: 2029
Use a split function to separate the first name & last name from the name list and traverse the list till the last element.
Code :
names = ['michelle rodriguez', 'dexter king', 'gurukavari']
firstname = []
for i in range(0,len(names)):
firstname.append(names[i].split()[0])
print(firstname)
Output :
['michelle', 'dexter', 'gurukavari']
Upvotes: 0
Reputation: 1109
You can use map function like:-
a = ['michelle rodriguez', 'dexter king', 'gurukavari']
b= map((lambda x: x.split()[0]), a) # ['michelle', 'dexter', 'gurukavari']
Upvotes: 1
Reputation: 853
Would advise to use Map
function, and to split each of the iterable items by space character, and return only the first of the split items.
Upvotes: 0
Reputation: 26039
Use a list-comprehension:
lst = ['michelle rodriguez', 'dexter king', 'gurukavari']
print([x.split()[0] for x in lst])
# ['michelle', 'dexter', 'gurukavari']
Upvotes: 4