Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional append/extend

Tags:

python

The methods append and extend in Python are not functional by nature, they modify the callee and return None.

Is there an alternative way to do what these methods do and get a new list as a returned value?

Consider this example:

def myfun(first, *args):
  for elem in [first].extend(args):
    print elem

Obviously, this won't work.

Is there a way to construct a new list "in place", instead of being forced to write the following?

def myfun(first, *args):
   all_args = list(first)
   all_args.extend(args)

   for elem in all_args:
     print elem

Thanks.

like image 643
Alexei Sholik Avatar asked Mar 15 '11 16:03

Alexei Sholik


1 Answers

You can rewrite that as:

[first] + args
like image 153
tangentstorm Avatar answered Sep 19 '22 18:09

tangentstorm