Join class list of lists

Viewed 76

I've got this method:

    def add_duty(self, new_duty):
        self.duty.append(new_duty)

which is used to append some duties to employees:

manager_employee[2].add_duty(['Do sth', 'Shine'])
manager_employee[2].add_duty(['Swag'])
manager_employee[2].add_duty(['Lag'])

If printed it shows duties in this way:

[['Do sth', 'Shine'], ['Swag'], ['Lag']]

I want to merge this list of lists into a single one. I've been trying to do that with regular ways of merging list of lists but it seems that class list behave in different way(I'm a newbie). And when merged it displays:

['D', 'o', ' ', 's', 't', 'h', 'S', 'h', 'i', 'n', 'e', 'S', 'w', 'a', 'g', 'Lag']

I'm looking for this effect:

['Do sth', 'Shine', 'Swag', 'Lag']

I've looked over some forums but found no answer.

3 Answers
l = [['Do sth', 'Shine'], ['Swag'], ['Lag']]

list_ = []

for i in l: list_ += i
print(list_)

Fix: To merge [['Do sth', 'Shine'], ['Swag'], ['Lag']] you can use a simple list-comprehension

a = [['Do sth', 'Shine'], ['Swag'], ['Lag']]
a = [word for sublist in a for word in sublist]

Best: it would be to modify your add_duty to add only words to the self.duty list, not list

def add_duty(self, new_duty):
    if isinstance(new_duty, list):
        self.duty.extend(new_duty)
    else:
        self.duty.append(new_duty)

# call like
manager_employee[2].add_duty(['Do sth', 'Shine']) # with a list
manager_employee[2].add_duty('Swag')              # with a string

Better: Use *args syntax, that takes all given argument and store them in a list

def add_duty(self, *new_duty):  # new_duty contains all parameters, as a list
    self.duty.extend(new_duty)

# call with any amount of string
manager_employee[2].add_duty('Do sth', 'Shine', 'other')
manager_employee[2].add_duty('Do sth', 'Shine')
manager_employee[2].add_duty('Swag')             

You can also use

from functools import reduce
l = [['Do sth', 'Shine'], ['Swag'], ['Lag']]
functools.reduce(lambda x,y: x+y, l, [])

if you want something similar to functional programming

Related