list = [[1,'abc'], [2, 'bcd'], [3, 'cde']]
I have a list that looks like above.
I want to parse the list and try to get a list that only contains the second element of all lists.
output = ['abc','bcd','cde']
I think I can do it by going over the whole list and add only the second element to a new list like:
output = []
for i in list:
output.append(i[1])
something like that, but please tell me if there is a better way.
You can use a list comprehension:
l = [[1,'abc'], [2, 'bcd'], [3, 'cde']]
new_l = [b for _, b in l]
Output:
['abc', 'bcd', 'cde']
Another way to do it is to use itemgetter
from operator
module:
from operator import itemgetter
l = [[1,'abc'], [2, 'bcd'], [3, 'cde']]
result = list(map(itemgetter(1), l))
print(result)
Output:
['abc', 'bcd', 'cde']
Another not so elegant way is to use the zip
function, take the second element from the newly created list and cast it to list
:
result = list(list(zip(*l))[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With