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:
lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']] lst2 = [item[0] for item in lst]
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:
lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']] # Extract first items of sublists lst2 = [item[0] for item in lst] # Print the extracted values print(lst2)
Output:
['a', 1, 'x']
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!