-2

Stating with

a = ['abc', 'efg', 'hij']

I want to get

a = ['abc!', 'efg!', 'hij!']

But obviously without the use of for elements in a:...because it is not cleaver and I want to understand more about the map function and how it passes parameters.

So I try to append a '!' to all elements of the lists using the map function. But before doing so, append is a list method but not a str method.

b = map(list,a) # gives : a = [['a','b','c'],['d','e','f'],['h','i','j']]
a = map(list.append(['!']), b) 

That last map function returns a TypeError:

TypeError: append() takes exactly one argument (0 given)

I wish to know if it is possible to pass parameter to the method used by map. Thank.

LAL
  • 480
  • 5
  • 13
  • You would need to incorporate a lamba but you should not use map for side effects and it will be slower than a regular loop, not sure why you think *But obviously without the use of for elements in a:...because it is not clever * as using map as you are is much worse an idea – Padraic Cunningham May 06 '16 at 20:21
  • I wanted to avoid people answering with a loop function. That's it. – LAL May 09 '16 at 13:01
  • I also think my question is related to "Understanding map function" but it is more specific. It isn't really a duplicate. Thanks for helping around :) – LAL May 09 '16 at 13:16

3 Answers3

2

You can get the expected result with following code:

a = ['abc', 'efg', 'hij']
map(lambda x: x + '!', a) # ['abc!', 'efg!', 'hij!']

First parameter of map is a function that is applied to all items on iterable which is the second parameter. You can't directly pass a parameter to the function given to map but you can create another function (or lambda) that passes the parameter just like in the example above.

Typically list comprehension should be favored over map because it more obvious what you are doing:

[x + '!' for x in a] # ['abc!', 'efg!', 'hij!']
Community
  • 1
  • 1
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

map receives two parameters, a function and a list.

It calls the function once for each of the items, with the current item as a parameter.

Converting the strings into lists and appending to them might not be the best choice, due to what map returns, but you can actually append to strings together using the + operator.

You can achieve what you want by doing the following:

map(lambda s: s + '!', a)  # => ['abc!', 'efg!', 'hij!']

lambda is just another syntax for a function, its parameter is named s, and it returns s + '!'.

Gilad Naaman
  • 6,390
  • 15
  • 52
  • 82
0

Using list comprehension:

>>> a = ['abc', 'efg', 'hij']
>>> ["{}!".format(x) for x in a]
['abc!', 'efg!', 'hij!']

How map works

map(function, iterator)

it takes element on by one and applies specified function to the each element

Example:

>>> def add_str(x):
...     return x+"!"
...
>>> a
['abc', 'efg', 'hij']
>>> map(add_str, a)
['abc!', 'efg!', 'hij!']
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Hackaholic
  • 19,069
  • 5
  • 54
  • 72