Unzipping and the * operator [duplicate] - python

This question already has answers here:
What do the * (star) and ** (double star) operators mean in a function call?
(4 answers)
Closed last month.
The python docs gives this code as the reverse operation of zip:
>>> x2, y2 = zip(*zipped)
In particular
zip() in conjunction with the * operator can be used to unzip a list.
Can someone explain to me how the * operator works in this case? As far as I understand, * is a binary operator and can be used for multiplication or shallow copy...neither of which seems to be the case here.

Although hammar's answer explains how the reversing works in the case of the zip() function, it may be useful to look at argument unpacking in a more general sense. Let's say we have a simple function which takes some arguments:
>>> def do_something(arg1, arg2, arg3):
... print 'arg1: %s' % arg1
... print 'arg2: %s' % arg2
... print 'arg3: %s' % arg3
...
>>> do_something(1, 2, 3)
arg1: 1
arg2: 2
arg3: 3
Instead of directly specifying the arguments, we can create a list (or tuple for that matter) to hold them, and then tell Python to unpack that list and use its contents as the arguments to the function:
>>> arguments = [42, 'insert value here', 3.14]
>>> do_something(*arguments)
arg1: 42
arg2: insert value here
arg3: 3.14
This behaves as normal if you don't have enough arguments (or too many):
>>> arguments = [42, 'insert value here']
>>> do_something(*arguments)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/blair/<ipython console> in <module>()
TypeError: do_something() takes exactly 3 arguments (2 given)
You can use the same construct when defining a function to accept any number of positional arguments. They are given to your function as a tuple:
>>> def show_args(*args):
... for index, value in enumerate(args):
... print 'Argument %d: %s' % (index, value)
...
>>> show_args(1, 2, 3)
Argument 0: 1
Argument 1: 2
Argument 2: 3
And of course you can combine the two techniques:
>>> show_args(*arguments)
Argument 0: 42
Argument 1: insert value here
You can do a similar thing with keyword arguments, using a double asterix (**) and a dictionary:
>>> def show_kwargs(**kwargs):
... for arg, value in kwargs.items():
... print '%s = %s' % (arg, value)
...
>>> show_kwargs(age=24, name='Blair')
age = 24
name = Blair
And, of course, you can pass keyword arguments through a dictionary:
>>> values = {'name': 'John', 'age': 17}
>>> show_kwargs(**values)
age = 17
name = John
It is perfectly acceptable to mix the two, and you can always have required arguments and optional extra arguments to a function:
>>> def mixed(required_arg, *args, **kwargs):
... print 'Required: %s' % required_arg
... if args:
... print 'Extra positional arguments: %s' % str(args)
... if kwargs:
... print 'Extra keyword arguments: %s' % kwargs
...
>>> mixed(1)
Required: 1
>>> mixed(1, 2, 3)
Required: 1
Extra positional arguments: (2, 3)
>>> mixed(1, 2, 3, test=True)
Required: 1
Extra positional arguments: (2, 3)
Extra keyword arguments: {'test': True}
>>> args = (2, 3, 4)
>>> kwargs = {'test': True, 'func': min}
>>> mixed(*args, **kwargs)
Required: 2
Extra positional arguments: (3, 4)
Extra keyword arguments: {'test': True, 'func': <built-in function min>}
If you are taking optional keyword arguments and you want to have default values, remember you are dealing with a dictionary and hence you can use its get() method with a default value to use if the key does not exist:
>>> def take_keywords(**kwargs):
... print 'Test mode: %s' % kwargs.get('test', False)
... print 'Combining function: %s' % kwargs.get('func', all)
...
>>> take_keywords()
Test mode: False
Combining function: <built-in function all>
>>> take_keywords(func=any)
Test mode: False
Combining function: <built-in function any>

zip(*zipped) means "feed each element of zipped as an argument to zip". zip is similar to transposing a matrix in that doing it again will leave you back where you started.
>>> a = [(1, 2, 3), (4, 5, 6)]
>>> b = zip(*a)
>>> b
[(1, 4), (2, 5), (3, 6)]
>>> zip(*b)
[(1, 2, 3), (4, 5, 6)]

When used like this, the * (asterisk, also know in some circles as the "splat" operator) is a signal to unpack arguments from a list. See http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists for a more complete definition with examples.

That's actually pretty simple once you really understand what zip() does.
The zip function takes several arguments (all of iterable type) and pair items from these iterables according to their respective positions.
For example, say we have two arguments ranked_athletes, rewards passed to zip, the function call zip(ranked_athletes, rewards) will:
pair athlete that ranked first (position i=0) with the first/best reward (position i=0)
it will move the the next element, i=1
pair the 2nd athlete with its reward, the 2nd from reward.
...
This will be repeated until there is either no more athlete or reward left. For example if we take the 100m at the 2016 olympics and zip the rewards we have:
ranked_athletes = ["Usain Bolt", "Justin Gatlin", "Andre De Grasse", "Yohan Blake"]
rewards = ["Gold medal", "Silver medal", "Bronze medal"]
zip(ranked_athletes, rewards)
Will return an iterator over the following tuples (pairs):
('Usain Bolt', 'Gold medal')
('Justin Gatlin', 'Silver medal')
('Andre De Grasse', 'Bronze medal')
Notice how Yohan Blake has no reward (because there are no more reward left in the rewards list).
The * operator allows to unpack a list, for example the list [1, 2] unpacks to 1, 2. It basically transform one object into many (as many as the size of the list). You can read more about this operator(s) here.
So if we combine these two, zip(*x) actually means: take this list of objects, unpack it to many objects and pair items from all these objects according to their indexes. It only make sense if the objects are iterable (like lists for example) otherwise the notion of index doesn't really make sense.
Here is what it looks like if you do it step by step:
>>> print(x) # x is a list of lists
[[1, 2, 3], ['a', 'b', 'c', 'd']]
>>> print(*x) # unpack x
[1, 2, 3] ['a', 'b', 'c', 'd']
>>> print(list(zip(*x))) # And pair items from the resulting lists
[(1, 'a'), (2, 'b'), (3, 'c')]
Note that in this case, if we call print(list(zip(x))) we will just pair items from x (which are 2 lists) with nothing (as there are no other iterable to pair them with):
[ ([1, 2, 3], ), (['a', 'b', 'c', 'd'], )]
^ ^
[1, 2, 3] is paired with nothing |
|
same for the 2nd item from x: ['a', 'b', 'c', 'd']
Another good way to understand how zip works is by implementing your own version, here is something that will do more or less the same job as zip but limited to the case of two lists (instead of many iterables):
def zip_two_lists(A, B):
shortest_list_size = min(len(A), len(B))
# We create empty pairs
pairs = [tuple() for _ in range(shortest_list_size)]
# And fill them with items from each iterable
# according to their the items index:
for index in range(shortest_list_size):
pairs[index] = (A[index], B[index])
return pairs
print(zip_two_lists(*x))
# Outputs: [(1, 'a'), (2, 'b'), (3, 'c')]
Notice how I didn't call print(list(zip_two_lists(*x))) that's because this function unlike the real zip isn't a generator (a function that constructs an iterator), but instead we create a list in memory. Therefore this function is not as good, you can find a better approximation to the real zip in Python's documentation. It's often a good idea to read these code equivalences you have all around this documentation, it's a good way to understand what a function does without any ambiguity.

I propose this one to unzip a zipped list of lists when zip is done with izip_longest:
>>> a =[2,3,4,5,6]
>>> b = [5,4,3,2]
>>> c=[1,0]]
>>>[list([val for val in k if val != None]) for k in
zip(*itertools.izip_longest(a,b,c))]
as izip_longest is appending None for lists shortest than the longest, I remove None beforehand. And I am back to the original a,b,c
[[2, 3, 4, 5, 6], [5, 4, 3, 2], [1, 0]]

Related

what is **eval() mean in python [duplicate]

In code like zip(*x) or f(**k), what do the * and ** respectively mean? How does Python implement that behaviour, and what are the performance implications?
See also: Expanding tuples into arguments. Please use that one to close questions where OP needs to use * on an argument and doesn't know it exists.
A single star * unpacks a sequence or collection into positional arguments. Suppose we have
def add(a, b):
return a + b
values = (1, 2)
Using the * unpacking operator, we can write s = add(*values), which will be equivalent to writing s = add(1, 2).
The double star ** does the same thing for a dictionary, providing values for named arguments:
values = { 'a': 1, 'b': 2 }
s = add(**values) # equivalent to add(a=1, b=2)
Both operators can be used for the same function call. For example, given:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
then s = add(*values1, **values2) is equivalent to s = sum(1, 2, c=10, d=15).
See also the relevant section of the tutorial in the Python documentation.
Similarly, * and ** can be used for parameters. Using * allows a function to accept any number of positional arguments, which will be collected into a single parameter:
def add(*values):
s = 0
for v in values:
s = s + v
return s
Now when the function is called like s = add(1, 2, 3, 4, 5), values will be the tuple (1, 2, 3, 4, 5) (which, of course, produces the result 15).
Similarly, a parameter marked with ** will receive a dict:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
this allows for specifying a large number of optional parameters without having to declare them.
Again, both can be combined:
def add(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = add(1, 2, 3, 4, 5) # returns 15
s = add(1, 2, 3, 4, 5, neg=True) # returns -15
s = add(1, 2, 3, 4, 5, neg=False) # returns 15
In a function call, the single star turns a list into separate arguments (e.g. zip(*x) is the same as zip(x1, x2, x3) given x=[x1,x2,x3]) and the double star turns a dictionary into separate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) given k = {'x':my_x, 'y':my_y}.
In a function definition, it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through x (i.e. if the user calls foo(1,2,3), x will be (1, 2, 3))" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".
I find this particularly useful for storing arguments for a function call.
For example, suppose I have some unit tests for a function 'add':
def add(a, b):
return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
print('test: adding', test, '==', result, '---', add(*test) == result)
There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.
Another place this is useful is for defining Factory objects (objects that create objects for you).
Suppose you have some class Factory, that makes Car objects and returns them.
You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.
def make_car(*args):
return Car(*args)
This is also useful when you want to call the constructor of a superclass.
It is called the extended call syntax. From the documentation:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.
and:
If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.

what does *line mean in this code? [duplicate]

In code like zip(*x) or f(**k), what do the * and ** respectively mean? How does Python implement that behaviour, and what are the performance implications?
See also: Expanding tuples into arguments. Please use that one to close questions where OP needs to use * on an argument and doesn't know it exists.
A single star * unpacks a sequence or collection into positional arguments. Suppose we have
def add(a, b):
return a + b
values = (1, 2)
Using the * unpacking operator, we can write s = add(*values), which will be equivalent to writing s = add(1, 2).
The double star ** does the same thing for a dictionary, providing values for named arguments:
values = { 'a': 1, 'b': 2 }
s = add(**values) # equivalent to add(a=1, b=2)
Both operators can be used for the same function call. For example, given:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
then s = add(*values1, **values2) is equivalent to s = sum(1, 2, c=10, d=15).
See also the relevant section of the tutorial in the Python documentation.
Similarly, * and ** can be used for parameters. Using * allows a function to accept any number of positional arguments, which will be collected into a single parameter:
def add(*values):
s = 0
for v in values:
s = s + v
return s
Now when the function is called like s = add(1, 2, 3, 4, 5), values will be the tuple (1, 2, 3, 4, 5) (which, of course, produces the result 15).
Similarly, a parameter marked with ** will receive a dict:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
this allows for specifying a large number of optional parameters without having to declare them.
Again, both can be combined:
def add(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = add(1, 2, 3, 4, 5) # returns 15
s = add(1, 2, 3, 4, 5, neg=True) # returns -15
s = add(1, 2, 3, 4, 5, neg=False) # returns 15
In a function call, the single star turns a list into separate arguments (e.g. zip(*x) is the same as zip(x1, x2, x3) given x=[x1,x2,x3]) and the double star turns a dictionary into separate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) given k = {'x':my_x, 'y':my_y}.
In a function definition, it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through x (i.e. if the user calls foo(1,2,3), x will be (1, 2, 3))" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".
I find this particularly useful for storing arguments for a function call.
For example, suppose I have some unit tests for a function 'add':
def add(a, b):
return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
print('test: adding', test, '==', result, '---', add(*test) == result)
There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.
Another place this is useful is for defining Factory objects (objects that create objects for you).
Suppose you have some class Factory, that makes Car objects and returns them.
You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.
def make_car(*args):
return Car(*args)
This is also useful when you want to call the constructor of a superclass.
It is called the extended call syntax. From the documentation:
If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.
and:
If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.

How to return an unpacked list in Python?

I'm trying to do something like this in python:
def f():
b = ['c', 8]
return 1, 2, b*, 3
Where I want f to return the tuple (1, 2, 'c', 8, 3). I found a way to do this using itertools followed by tuple, but this is not very nice, and I was wondering whether there exists an elegant way to do this.
The unpacking operator * appears before the b, not after it.
return (1, 2, *b, 3)
# ^ ^^ ^
However, this will only work on Python 3.5+ (PEP 448), and also you need to add parenthesis to prevent SyntaxError. In the older versions, use + to concatenate the tuples:
return (1, 2) + tuple(b) + (3,)
You don't need the tuple call if b is already a tuple instead of a list:
def f():
b = ('c', 8)
return (1, 2) + b + (3,)
Note the accepted answer explains how to unpack some values when returning them as part of a tuple that includes some other values. What if you only want to return the unpacked list? Following up on a comment above:
def func():
list1 = [1,2,3]
return *list1
This gives SyntaxError: invalid syntax.
The solution is to add parentheses ( and ) and a comma , after the return value, to tell Python that this unpacked list is part of a tuple:
def func():
list1 = [1,2,3]
return (*list1,)

List as Function Arguments in Python

If I were trying to input a list as an argument to a function in Python, is there any way to retain the argument as a list or will it have to be passed in one element at a time?
If you pass the list as is, then it will stay as a list.
>>> def myfunc(*args):
for arg in args:
print(arg)
>>> sample_list = [1, 2, 3]
>>> myfunc(sample_list)
[1, 2, 3]
The function prints the list as one item.
However, if you use the 'splat' or 'unpack' operator *, the list can be passed as multiple arguments.
>>> myfunc(*sample_list)
1
2
3
This is not an answer but it's hard to make code in comments/
Probably you meant this:
def f(a, b):
print("f(%s, %s)" % (a, b))
l = [1, 2]
f(*l)
The syntax you are looking for is this:
my_list = ["arg1", "arg2", None, 4, "arg5"]
print(*my_list)
is equivalent to:
print("arg1", "arg2", None, 4, "arg5")
You get the object inside the function that you pass as argument. If your argument is a list, then you get a list inside the function, of course as one proper list and not as single variables.
def func1(my_list):
print(type(my_list), my_list)
func1([1, 2, "abc"])
# output: <type 'list'> [1, 2, "abc"]
However, you can use several ways to achieve something else. You can...
Pass single arguments when calling the function, but receive all of them as single tuple (immutable list).
def func2(*my_list): # the * means that this parameter collects
# all remaining positional arguments
print(type(my_list), my_list)
func2(1, 2, "abc")
# output: <type 'tuple'> (1, 2, "abc")
Unpack a list in the function call and receive the elements as single arguments.
def func2(arg1, arg2, arg3):
print(type(arg1), arg1, type(arg2), arg2, type(arg3), arg3)
func2(*[1, 2, "abc"]) # the * unpacks the list to single positional arguments
# output: <type 'int'> 1 <type 'int'> 2 <type 'str'> abc

How to call a pre-define function in python using map()? [duplicate]

The Python 2 documentation says:
Built-in Functions: map(function, iterable, ...)
Apply function to every item of iterable and return a list of the
results. If additional iterable arguments are passed, function must
take that many arguments and is applied to the items from all
iterables in parallel.
If one iterable is shorter than another it is assumed to be extended
with None items.
If function is None, the identity function is assumed; if there are
multiple arguments, map() returns a list consisting of tuples
containing the corresponding items from all iterables (a kind of
transpose operation).
The iterable arguments may be a sequence or any iterable object; the
result is always a list.
What role does this play in making a Cartesian product?
content = map(tuple, array)
What effect does putting a tuple anywhere in there have? I also noticed that without the map function the output is abc and with it, it's a, b, c.
I want to fully understand this function. The reference definitions is also hard to understand. Too much fancy fluff.
map isn't particularly pythonic. I would recommend using list comprehensions instead:
map(f, iterable)
is basically equivalent to:
[f(x) for x in iterable]
map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:
[(a, b) for a in iterable_a for b in iterable_b]
The syntax is a little confusing -- that's basically equivalent to:
result = []
for a in iterable_a:
for b in iterable_b:
result.append((a, b))
map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.
map in Python 3 is equivalent to this:
def map(func, iterable):
for i in iterable:
yield func(i)
and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.
Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:
[func(i) for i in iterable]
As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -
>>> a = "hello, world"
>>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:
>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:
>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
map creates a new list by applying a function to every element of the source:
xs = [1, 2, 3]
# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
ys.append(x * 2)
n-ary map is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:
xs = [1, 2, 3]
ys = [2, 4, 6]
def f(x, y):
return (x * 2, y // 2)
# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
zs.append(f(x, y))
I've used zip here, but map behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None.
Simplifying a bit, you can imagine map() doing something like this:
def mymap(func, lst):
result = []
for e in lst:
result.append(func(e))
return result
As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map() can process more than one iterable:
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.
For the second part in the question: What role does this play in making a Cartesian product? well, map() could be used for generating the cartesian product of a list like this:
lst = [1, 2, 3, 4, 5]
from operator import add
reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))
... But to tell the truth, using product() is a much simpler and natural way to solve the problem:
from itertools import product
list(product(lst, lst))
Either way, the result is the cartesian product of lst as defined above:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
(2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.
Let's look at an example:
map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.
Imagine you have a function that takes a number, adds 1 to that number and returns it:
def add_one(num):
new_num = num + 1
return new_num
You also have a list of numbers:
my_list = [1, 3, 6, 7, 8, 10]
if you want to increment every number in the list, you can do the following:
>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]
Note: At minimum map() needs two arguments. First a function name and second something like a list.
Let's see some other cool things map() can do.
map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.
We have three lists:
list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]
map() can make you a new list that holds the addition of elements at a specific index.
Now remember map(), needs a function. This time we'll use the builtin sum() function. Running map() gives the following result:
>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]
REMEMBER:
In Python 2 map(), will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. In Python 3 map() will stop after finishing with the shortest list. Also, in Python 3, map() returns an iterator, not a list.
Python3 - map(func, iterable)
One thing that wasn't mentioned completely (although #BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.
import time
def test1(iterable):
a = time.clock()
map(str, iterable)
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
def test2(iterable):
a = time.clock()
[ x for x in map(str, iterable)]
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
test1(range(2000000)) # Prints ~1.7e-5s ~8s
test2(range(2000000)) # Prints ~9s ~8s
As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.

Categories