How to Slice the Second Element of a List of Lists in Python?

Estimated read time 1 min read

To slice the second element of a list of lists in Python, you can use the following syntax:

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

second_elements = [sublist[1] for sublist in my_list]

print(second_elements)

In this example, we define a list of lists my_list containing three sublists.

We use a list comprehension to slice the second element of each sublist in my_list. The expression sublist[1] accesses the second element of each sublist. The list comprehension returns a new list containing the second element of each sublist.

Finally, we print the new list second_elements.

Note: If you only need the second element of the first sublist, you can use my_list[0][1].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply