0

I am very new to python and just wondering how to rewrite this code without using lambda so I get a better understanding of solving problems in different ways.

I want to print out only even numbers from this list:

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

ouput: [4,6,8,12]
George Mauer
  • 117,483
  • 131
  • 382
  • 612
Rebecca
  • 3
  • 2
  • 1
    Hi Rebecca, welcome to StackOverflow. I'll note that this question may not be the best fit for this site which aims more to have questions with concrete answers and this one is more soliciting a range of opinions. A good place for it might be [on the code review stackexchange](https://codereview.stackexchange.com/) – George Mauer Jun 04 '20 at 21:15
  • What were the results of your research into alternatives to lambdas? – quamrana Jun 04 '20 at 21:19

2 Answers2

0
new_list = [x for x in my_list if x%2==0]

I believe this should work, if you don't like list comprehension, then I suggest the following:

new_list=[]

for i in my_list:
    if i%2 == 0:
        new_list.append(i)

0

Ways to iterate through a list in python

Functionally

Using map, filter, reduce as you have in your question.

Iterativly

With a for loop

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = []
for num in my_list:
    if num % 2 == 0:
         new_list.append(num)

print(new_list)
# outputs: [4,6,8,12]

With a list comprehension (also a for loop, but special)

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = [num for num in my_list if num % 2 == 0]  # compact edition
new_list = [  # more readable edition
    num
    for num in my_list
    if num % 2 == 0
]

print(new_list)
# outputs: [4,6,8,12]
masq
  • 123
  • 1
  • 8