python | Get first elements of 2d list

Viewed 102

i have following List:

j = [
    [(1, 100), (2, 80), (3, 40)],
    [(2, 80), (1, 30), (4, 50), (3, 60)],
    [(1, 40), (2, 70), (4, 30)]
]

How can i print every first element like this:

[1, 2 ,3]
[2, 1, 4, 3]
[1, 2, 4]

I tried with

for i in j:
print(i[0])

Thanks!

4 Answers

Using zip and a list comprehension:

[next(zip(*i)) for i in j]

[(1, 2, 3), (2, 1, 4, 3), (1, 2, 4)]

Or using a nested loop:

[[v[0] for v in i] for i in j]

[[1, 2, 3], [2, 1, 4, 3], [1, 2, 4]]

Try this:

for i in j:
    print([v[0] for v in i])

The ugliest, least pythonic form, but easiest to understand:

list_of_tuples = [[(1, 100), (2, 80), (3, 40)],
    [(2, 80), (1, 30), (4, 50), (3, 60)],
    [(1, 40), (2, 70), (4, 30)]]
    

for tuple_ in list_of_tuples : # iterating over the list items, i.e. the tuples
   storage_list=[] # creating an empty list for storage of items we want to print
   for item in tuple_: # iterating over the tuple items
      storage_list.append(item[0]) # storing the first item of each tuple in the created list
   print(storage_list)

Output:

[1, 2, 3]
[2, 1, 4, 3]
[1, 2, 4]

You can use python's list comprehensions for each list i:

for i in j:
    print([x for x,y in i])

If you haven't used list comprehensions before, this means for each item in the list i (in this case a tuple (x,y)), use the value of x for this new list we are creating.

Related