0

Does someone know the difference between these two and why? lambda doesn't not allow to reverse a single string?

Works fine with this

s = ['justdoit','asdf']
list(map(lambda s: s[::-1], s))

Doesn't apply the slicer. But why?

s = 'justdoit'
list(map(lambda s: s[::-1], s))
1
  • 1
    Strings and lists are both iterables but their elements differ: list elements are items in list and string elements are characters in string. So in case of list you apply lambda to item in list (in this case a word) and in case of string you apply lambda to a character. Commented Oct 29, 2019 at 7:11

3 Answers 3

3

It is applying the slicer, but because a string is iterable, it's being applied to each single letter of s, and the reversal of a single-letter string is just the single letter.

For example:

>>> map(lambda x: print(x), 'justdoit')
>>> list(map(lambda x: print(x), 'justdoit'))
j
u
s
t
d
o
i
t
[None, None, None, None, None, None, None, None]

and so

>>> s = 'justdoit'
>>> list(map(lambda s: s[::-1], s))
['j', 'u', 's', 't', 'd', 'o', 'i', 't']  # 'j' reversed, 'u' reversed, etc
Sign up to request clarification or add additional context in comments.

Comments

0

I think this boils down to how python/lambda interprets strings and arrays. When you pass a single string in your 2nd attempt, the lambda takes it in as an array of characters. Where as in the first attempt, it receives it as an array of string objects to work on. If you want to reverse even a single string, you will need to pass it as an array of single string.

Eg.

s = ['justdoit']
list(map(lambda s: s[::-1], s))

This should work

Comments

0

python map applies on a list. So you need to wrap the string into a list.

s = ['justdoit']

1 Comment

isn't it a list as well? A list with only one string element..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.