manjula manjula - 3 days ago 6
Python Question

How to create a new list based on the values of the existing list?

I am new to python.

Let's say I have a list like this :

randomList = [2, 3, 5, 7, 11]


How to filter the values of above list such that the new resultant list has the values according to the condition mentioned.

For example :

Lets say I want to create a new list of all the numbers
n * 2
in randomList such that
n%2 != 0
. Therefore, the new list should look something like this :

newList = [6, 10, 14, 22]


I can do this by using a
for
loop and using
append
command, but is there a better way to this in python?

p.s - I am a beginner.

Answer

You could do that in one simple line.

randomList = [2, 3, 5, 7, 11]

newList = [n*2 for n in randomList if n%2 != 10]

That's it.

Now the values in newList would be :

newList = [6, 10, 14, 22]
Comments