Home > Software design >  Creating a new list by extracting first and last element of a nested list in python
Creating a new list by extracting first and last element of a nested list in python

Time:10-06

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)

CodePudding user response:

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']
  • Related