Categories
Python Answers

How to extract first item of each sublist with Python?

Spread the love

Sometimes, we want to extract first item of each sublist with Python.

In this article, we’ll look at how to extract first item of each sublist with Python.

How to extract first item of each sublist with Python?

To extract first item of each sublist with Python, we can use list comprehension.

For instance, we write:

lst = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
lst2 = [item[0] for item in lst]
print(lst2)

to get the first item from each list in lst by getting item[0] from each item, which is each list in lst.

Therefore, lst2 is ['a', 1, 'x'].

Conclusion

To extract first item of each sublist with Python, we can use list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *