user1749431
user1749431

Reputation: 569

Get indexposition from nested list

I have a nested list

nested_list = [["cats", "dogs", "cars"], ["dogs", "green", ", "red"], ["cars", "black", "purple"]]

and I need to get each index position [1] in the range of the nested_list so I get the resulting list ["cats", "dogs", "cars"]

Upvotes: 1

Views: 69

Answers (2)

jabaldonedo
jabaldonedo

Reputation: 26572

An easy way to do that is using list comprehension in Python.

>>> nested_list = [["cats", "dogs", "cars"], ["dogs", "green", "", "red"], ["cars", "black", "purple"]]
>>> res = [l[0] for l in nested_list]
 ['cats', 'dogs', 'cars']

By the way, you say you want to get each element of position 1, however in your example you are getting position 0, Python starts counting at position 0

Upvotes: 1

MB-F
MB-F

Reputation: 23637

You can use a list comprehension to build a resulting list from the desired index positions.

result = [sublist[0] for sublist in nested_list]

Btw, python indexing starts with 0.

Upvotes: 2

Related Questions