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

DDD
Release: 2024-11-22 09:33:16
Original
352 people have browsed it

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

For example:

lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
Copy after login

Using the list comprehension, we can extract the first items:

lst2 = [item[0] for item in lst]
Copy after login
Copy after login

Result:

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

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!

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