'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?



Solution 1:[1]

Use a list-comprehension:

lst = ['michelle rodriguez', 'dexter king', 'gurukavari'] 
print([x.split()[0] for x in lst])

# ['michelle', 'dexter', 'gurukavari']

Solution 2:[2]

You can use map function like:-

a = ['michelle rodriguez', 'dexter king', 'gurukavari'] 
b= map((lambda x: x.split()[0]), a) # ['michelle', 'dexter', 'gurukavari']

Solution 3:[3]

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.

Solution 4:[4]

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']

Solution 5:[5]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Austin
Solution 2 Rupal
Solution 3 Kox
Solution 4 Usman
Solution 5 Saurabh Chandra Patel