2

I have this bit of a practice code:

even = []
odd = []

for x in range(1000):
    if x % 2 != 0:
        odd.append(x)
    else:
        even.append(x)

print map(lambda x: x if str(x)[-1] == '2' else pass, even)

print even
print odd

In my mind, I should get in the end full list of odd numbers in 0 - 999 range and a list of even numbers from the same range which do not end with "2". In practice however, I keep on getting syntax error pointing to the "pass" in lambda expression.

What am I doing wrong here?

Cheers, Greem

1
  • You're doing extra work by making a string. Try x % 10 == 2 Commented Apr 9, 2017 at 3:02

3 Answers 3

2

pass is a statement, but inline if, being an operator, needs its operands to be expressions. map can’t actually remove elements from the sequence, but filter (returns a new list with only the values for which the function returns True) can:

print filter(lambda x: str(x)[-1] == '2', even)
Sign up to request clarification or add additional context in comments.

Comments

2

If you're like me and don't like filters and lambda, you can accomplish this with Python list comprehension:

print [x for x in even if str(x)[-1] == '2']

Comments

1
even = []
odd = []

for x in range(1000):
    if x % 2 != 0:
        odd.append(x)
    else:
        even.append(x)

print (filter(lambda x: str(x)[-1] == '2', even))

print (even)
print (odd)

Will work on python 3 too..

Comments

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.