Python – Get First Element of Each Sublist

In this tutorial, we will look at how to extract the first element of each sublist from a list of lists in Python.

Let’s look at some methods with the help of examples.

The straightforward way is to loop over each sublist in the list of lists and append its first element to our result list.

```# create a list of lists
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# get first element of each sublist
result = []
for ls in a:
result.append(ls[0])
# display the result
print(result)```

Output:

`[1, 4, 7]`

We get a list of the first items in each sublist.

You can also use list comprehension to reduce to above code to a single line.

```# create a list of lists
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# get first element of each sublist
result = [ls[0] for ls in a]
# display the result
print(result)```

Output:

`[1, 4, 7]`

We get the same result as above.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

You can similarly use the above methods to get the last element in each sublist. Use the `-1` index to access the last element from a list. Let’s use the list comprehension method to get a list of all the last elements in the original list.

```# create a list of lists
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# get last element of each sublist
result = [ls[-1] for ls in a]
# display the result
print(result)```

Output:

`[3, 6, 9]`

You can see that the new list has only the last elements from the sublists in the original list.

You might also be interested in –