2

I have a list of lists, each sub-list contain exactly 2 floats:

my_list = [[0, 1], [0, 1], [0, 1]]

Is there a one liner slice operation; so as to not have a for loop?

Desired Output:

> [[1], [1], [1]]

Then, I would like to merge these sub-lists as elements into one list. Outputting, as dtype list:

> [1, 1, 1]

Failed attempt:

d_[:][1]
> [[0, 1]]
  • 1
    `[i[1] for i in my_list]` or `list(map(itemgetter(1), my_list))` ([`itemgetter`](https://docs.python.org/3/library/operator.html#operator.itemgetter)) – Olvin Roght May 13 '21 at 12:29

1 Answers1

1

You can use list comprehension

ans = [x[1] for x in my_list]

Full answer:

my_list = [[0, 1], [0, 1], [0, 1]]
ans = [x[1] for x in my_list]

print(ans)

>>> [1, 1, 1]
artemis
  • 6,857
  • 11
  • 46
  • 99
  • If it works it works. Thank you :). I wanted to try slicers because I couldn't get a for loop to work, but your solution does work. – ThePewCDestroyer May 13 '21 at 12:31
  • 1
    In this case, you are _kind_ of using slice notation anyway, since you are accessing the `n-th` item of a list (in this case, we just specified `n`). Slicing is nice if you want to take a subset of a list, but we really just want a single element :). If this answered your question, remember to accept it so that it can help others as well. – artemis May 13 '21 at 12:33