I have a 2D list:
items = [['a','b'],['c','d']]
I would like to get a new list containing the last element of each nested list:
new_list = ['b','d']
I can do it like so:
new_list = []
for i in items:
new_list.append(i[-1])
But this feels very clumsy for such a simple thing. I was wondering if there was a more elegant way of doing this.
CodePudding user response:
If you have...
items = [
['a', 'b'],
['c', 'd']
]
...you have a nested list that you can access this way:
>>> items[0]
['a', 'b']
>>> items[0][0]
To have the second element (the element with index 1
) of each sublist, I would suggest a list comprehension:
new_list = [sublist[1] for sublist in items]
If you want the last element (the element with index -1
) of each sublist, you just have to change the index:
new_list = [sublist[-1] for sublist in items]
For the list you shown the two lines will give the same list, but when the sublists have more than two elements the two solution will give different results.
You can read more about list comprehension here
and here
.
CodePudding user response:
From a readability perspective, I would probably combine iterable unpacking with list comprehension for something like -
new_list = [second for first, second, *rest in items]
The *rest
is not really required in this case where the sublists have only 2 items, but helps generalize.
CodePudding user response:
You can do
new_list = [i[-1] for i in items]