5

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.

1
  • 1
    Using list as a variable name isn't recommended. You could always do [x[1] for x in my_list], or list(map(lambda x: x[1],my_list)) if you are in a Lispy mood. Commented Mar 22, 2018 at 19:14

2 Answers 2

7

You can use a list comprehension:

l = [[1,'abc'], [2, 'bcd'], [3, 'cde']]
new_l = [b for _, b in l]

Output:

['abc', 'bcd', 'cde']
Sign up to request clarification or add additional context in comments.

Comments

3

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.