Nienke Luirink
Nienke Luirink

Reputation: 141

Extracting first names from list of full names in Python

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

Answers (5)

Saurabh Chandra Patel
Saurabh Chandra Patel

Reputation: 13586

name = "Saurabh Chandra Patel"
first_name = name.rsplit(' ', 1)[0]
last_name = name.rsplit(' ', 1)[1]
  1. first_name = Saurabh Chandra
  2. last_name = Patel

if name = "Saurabh Patel"

  1. first_name = Saurabh
  2. last_name = Patel

Upvotes: 0

Usman
Usman

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

Rupal
Rupal

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

Kox
Kox

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

Austin
Austin

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

Related Questions