Extracting First Items from Nested Lists in Python
Given a list of lists, the task is to extract the first item from each sublist and create a new list containing those values. For instance, with a list like [[a,b,c], [1,2,3], [x,y,z]], the desired output would be [a, 1, x].
Solution Using List Comprehension:
A straightforward approach involves using list comprehension:
1 2 |
|
This comprehension iterates over each sublist in lst and selects the first item using the item[0] expression. The extracted values are then appended to the new list, lst2.
Example:
Consider the following example:
1 2 3 4 5 6 7 |
|
Output:
1 |
|
The above is the detailed content of How to Extract the First Item from Each Sublist in a Nested Python List?. For more information, please follow other related articles on the PHP Chinese website!