0

I was wondering if there was a one-liner in Python that would allow me to get the first character out of every string in a given list in Python. I can accomplish this task with the following code, however I was hoping there was a cleaner way to do it. By cleaner I mean using a built-in function, or using a one-liner that accomplishes the same thing as this for loop. Please let me know if there is a cleaner way and if I need to clarify anything further.

names = ['Sally', 'Tom']
firstCharList = []
for name in names:
    firstCharList.append(name[0])
print(firstCharList)

Output: ['S', 'T']

AndreasKralj
  • 463
  • 4
  • 23
  • Does [this](https://stackoverflow.com/questions/30062429/how-to-get-every-first-element-in-2-dimensional-list) answer your question? Note the same idea applies since a `str` is just a sequence of characters, same solution works here. – Cory Kramer Jul 23 '21 at 15:33
  • Does this answer your question? [Python: Get the first character of the first string in a list?](https://stackoverflow.com/questions/7108080/python-get-the-first-character-of-the-first-string-in-a-list) – mpx Jul 23 '21 at 15:45
  • @balandongiv No, because list comprehension was what I was missing. The accepted answer there only shows indexing into the list and not using list comprehension. – AndreasKralj Jul 23 '21 at 15:47
  • 1
    Cory's answer illustrates the same concept and does answer my question, though new programmers may not be familiar with the fact that a string is just a sequence of characters that can be indexed and therefore may not make the connection that they can use list comprehension for that as well. I've selected SorousH's answer as the accepted one and would recommend leaving this answer up; however, I'll leave it up to the community regarding whether this should be closed as a duplicate or left open for others to find – AndreasKralj Jul 23 '21 at 15:52

1 Answers1

2

list comprehension is more readable.

names = ['Sally', 'Tom']
print([item[0] for item in names])

output :

['S', 'T']
S.B
  • 13,077
  • 10
  • 22
  • 49