-1
name = ['Marina Allison', 'Markus Valdez', 'Connie Ballard', 'Darnell Weber', 'Sylvie Charles', 'Vinay Padilla', 'Meredith Santiago', 'Andre Mccarty', 'Lorena Hodson', 'Isaac Vu']

# how can I get the first name for ex. Marina 

Name is the list of random names. I've tried joining it with .join()

  • Does this answer your question? [Iterate a list with indexes in Python](https://stackoverflow.com/questions/126524/iterate-a-list-with-indexes-in-python) – ytan11 Dec 29 '21 at 04:34
  • What do you imagine are the logical steps to solving the problem? Where are you stuck? – Karl Knechtel Aug 08 '22 at 01:41

3 Answers3

2

Try in this way:

name = ['Marina Allison', 'Markus Valdez', 'Connie Ballard', 'Darnell Weber', 'Sylvie Charles', 'Vinay Padilla', 'Meredith Santiago', 'Andre Mccarty', 'Lorena Hodson', 'Isaac Vu']

for i in name:
    print(i.split(' ')[0])
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
2

Your question is somewhat ambiguous, so I'll provide an answer for the interpretations I find most obvious.

Firstly, given a full-name string name = "First Last", I would recommend these approaches to getting just the First portion of the string:

  1. Find the space and splice the string. This is arguably the most efficient method.
first_name = name[:name.find(" ")]

In Python, strings are character lists. name.find(" ") returns the index of the first occurrence of " ". Using this index, we splice the string and take only its characters preceding the space.

  1. Split at the space and select the first element.
first_name = name.split()[0]   # split at whitespace, take first element

split() with no specified input argument splits on all white space, including spaces, newlines, carriage returns, etc, and returns a list of the elements separated by each of these whitespace characters. This is less efficient than the first solution but more concise.

Now, to apply this on the entire name list to obtain a list of only the first names, I offer these two code snippets:

First, the more straightforward approach

first_names = []
for elem in name:
    first_names.append(elem[:elem.find(" ")])

Next, using functional programming tools

first_names = list(map(lambda x: x[:x.find(" ")], name))

To print the result of either of these:

print("\n".join(first_names))

or

for x in first_names:
    print(x)
monty
  • 61
  • 4
0

Using list comprehension, one can get first name as list:

[x.split()[0] for x in name] o/p: ['Marina', 'Markus', 'Connie', 'Darnell', 'Sylvie', 'Vinay', 'Meredith', 'Andre', 'Lorena', 'Isaac']

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 31 '21 at 01:45