How to Extract the First Item from Each Sublist in a Nested Python List?

DDD
Release: 2024-11-23 20:05:14
Original
181 people have browsed it

How to Extract the First Item from Each Sublist in a Nested Python List?

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]
Copy after login

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)
Copy after login

Output:

['a', 1, 'x']
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template