Combines a for loop into the creation of a new list based on an existing list.

new_list = [<expression> for <element> in <collection>]


source = [1, 2, 3, 4]
NewList = [item * 2 for item in source]
print(NewList)    //Will print: [2, 4, 6, 8]

Adding conditional arguments

if

You simply add an if statement to the end:

new_list = [<expression> for <element> in <collection> if <expression>]


source = [1, 2, 3, 4]
NewList = [item * 2 for item in source if item >= 2]
print(NewList)    //Will print: [6, 8]
if else
new_list = [<expression> for <element> in <collection> if <expression>]


source = [1, 2, 3, 4]
NewList = [item * 2 if item >= 2 else item * 1 for item in source]
print(NewList)    //Will print: [1, 2, 6, 8]

Examples

Create list with 100 entries of 0
my_list = [0 for i in range(5)]    #Create a list 5 entries long containing 0
Create list with 100 random entries
random_list = [random.randint(0, 100) for i in range(5)]    #Create a list 5 entries long that has a random number in each from 0 to 100 (inclusive)
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *