How to extract the first item of each sublist with Python?

Estimated read time 2 min read

To extract the first item of each sublist in Python, you can use a list comprehension or a for loop. Here’s an example using a list comprehension:

my_list = [['apple', 'banana', 'cherry'], ['dog', 'cat', 'bird'], ['red', 'green', 'blue']]
first_items = [sublist[0] for sublist in my_list]
print(first_items) # Output: ['apple', 'dog', 'red']

In this example, we have a list of sublists called my_list. We use a list comprehension to extract the first item of each sublist. The list comprehension iterates over each sublist using the for loop, and retrieves the first item of each sublist using the [0] index.

The resulting list of first items is stored in a variable called first_items, and then printed using the print() function.

You can also achieve the same result using a for loop:

my_list = [['apple', 'banana', 'cherry'], ['dog', 'cat', 'bird'], ['red', 'green', 'blue']]
first_items = []
for sublist in my_list:
    first_items.append(sublist[0])
print(first_items) # Output: ['apple', 'dog', 'red']

In this example, we create an empty list called first_items, and use a for loop to iterate over each sublist in my_list. Inside the loop, we append the first item of each sublist to the first_items list using the .append() method.

Finally, we print the first_items list using the print() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply