Home  >  Article  >  Backend Development  >  How to Extract the First Element from Each Sublist in a Python List?

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

DDD
DDDOriginal
2024-11-22 09:33:16370browse

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!

Statement:
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