Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

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 a 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 are also hard to understand. Too much fancy fluff.

3 Answers

0 votes
by (106k points)

map on 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 as follows:

result = [] 

for a in iterable_a: 

for b in iterable_b: 

result.append((a, b))

To know more about this you can have a look at the following video tutorial:-

0 votes
by (20.3k points)

Map always 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))

You can also use 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.

0 votes
by (20.3k points)

You can try calling decode() on a bytes instance to get the text which it encodes

str = bytes.decode()

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...