This tutorial will discuss about unique ways to get first character of each string in list in Python.
Table Of Contents
Method 1: Using map() method
In this solution, we are assuming that your list has string elements only.
Create a lambda function
, that accept a string as argument, and returns the first character of that string. Using map()
method, apply this lambda function
on each element of list and store the returned characters in a mapped object. Then create a list from all those characters in the mapped object. Basically this list will have the first character of each string in List.
Let’s see the complete example,
listOfStrs = ['This', 'is', 'a', 'sample', 'string'] # Apply a lambda function on each element of string # to fetch first character of each string charList = list(map(lambda elem: elem[0], listOfStrs)) print(charList)
Output
['T', 'i', 'a', 's', 's']
Method 2: Using List comprehension and isinstance()
What if list has some non string values too? In that case we want to get a list of first characters of string elements from list only. We can skip the non string elements. For that, we can iterate over all elements of list, using a List comprehension and select first character from only string elements. It will return a list of first character of each string in List.
Frequently Asked:
To check if an element is of string type or not, we have used the isinstance() method.
Let’s see the complete example,
listOfStrs = ['This', 'is', 'a', 56, 'sample', 'string'] # Select first character of string elements from list charList = [elem[0] for elem in listOfStrs if isinstance(elem, str)] print(charList)
Output
['T', 'i', 'a', 's', 's']
Method 3: Using for-loop
This is exactly similar to previous solution, but we have used the for-loop instead of List comprehension to select first character from each string in list.
Let’s see the complete example,
listOfStrs = ['This', 'is', 'a', 56, 'sample', 'string'] charList = [] # Select first character of string # elements from the list for elem in listOfStrs: if isinstance(elem, str): charList.append(elem[0]) print(charList)
Output
['T', 'i', 'a', 's', 's']
Summary
We learned about different ways to access the first character of each string in a List in Python. Thanks.