Home > Article > Backend Development > How to Extract the First Element from Each Sublist in a Python List?
Extracting First Items of Sublists in Python
Given a list of lists, a common task is to extract the first item from each sublist and create a new list with these items.
Using List Comprehension
One efficient way to achieve this is through list comprehension:
lst2 = [item[0] for item in lst]
For example:
lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
Using the list comprehension, we can extract the first items:
lst2 = [item[0] for item in lst]
Result:
['a', 1, 'x']
This approach creates a new list, lst2, containing the first items of each sublist in lst.
The above is the detailed content of How to Extract the First Element from Each Sublist in a Python List?. For more information, please follow other related articles on the PHP Chinese website!