Python Forum
Write one line of Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write one line of Python
#1
Hey guys
I have been trying to find a solution or this exercise and I actually did . But the problem is that I can not actually write this program in one line of Python !
I don't know how to do it Think
'''
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.
'''
And this is my code :
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
new_list = []
for i in a:
    if i % 2 == 0:
        new_list.append(i)
print(new_list)
Reply
#2
Look into list comprehensions.

foo = [x for x in range(20) if x > 10]
The above list comprehension won't solve you problem, but that's the format your solution is going to take. Think about how your loop maps to that list comprehension.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Aug-18-2019, 02:27 PM)ichabod801 Wrote: Look into list comprehensions.

foo = [x for x in range(20) if x > 10]
The above list comprehension won't solve you problem, but that's the format your solution is going to take. Think about how your loop maps to that list comprehension.
thanks
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020