Search code examples
pythonnested-lists

Creating a new list by extracting first and last element of a nested list in python


I want to extract first and last elements form a nested list and create a new list from that. This is my code. Expected result should be [True, False, 'a', 'z'], however the output I get is [[True, False], ['a', 'z']] Any insight on how to correct this, so that my output is a new list?

def first_and_last(l):
    result = []
    for x in l:
        result.append([x[0], x[-1]])
    return result

fl = first_and_last([[True, True, False], ['a', 'b', 'z']])
print(fl)

Solution

  • Instead of appending, extension of string shall work;

    def first_and_last(l):
        result = []
        for x in l:
            # result = result + [x[0], x[-1]]
            result.extend((x[0], x[-1]))          # This one is faster than + sign extension of list
        return result
    
    fl = first_and_last([[True, True, False], ['a', 'b', 'z']])
    print(fl)
    
    # [True, False, 'a', 'z']