Lambda Expressions + List Slicing


hello everyone,

I have a question about lambda expressions. Just after the list slicing exercise, I wanted to use list slicing in filter. But it didn't work.

I don't know if my syntax was wrong, or if this approach is useless.

Your comments will be appreciated! Thanks

I have the error message below, looks like slicing didn't work at all

Oops, try again. It looks like your message is "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" instead of "I am another secret message!"

message = filter(lambda x: x[::3],garbled)
print message


The thing is.....garbled is not a list....


Which operator would you use to identify something that is not a character you want displayed?


good point :slight_smile: thanks


Strings are slicable as well.
You're slicing x though, not garbled. You have to consider what x is before doing anything with it, in other words, you'll need to think again about how the filter function behaves - filter calls your function once for each value in the sequence, and each value in a string is a single-letter string. The function should also not be returning a string, it should be telling filter whether to include or exclude the given value.


The tricky part is, if you take a close look at the provided list, all the "X"s here don't have the same distance as the test you took before, that's why you can't just simply fix the message by defining a stride.

message = filter(lambda x: x != "X", garbled)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.