Variables

List Comprehensions in Python

List comprehension is used to dynamically generate lists.


Syntax
#generating a list with a filter
list_name = [var for var in existing_list boolean_expression] #boolean_expression is optional

#generating a list and applying an operation (multiplication, dividing, etc.) to each element
list_name2 = [(var_with_operations) for var in existing_list]

Notes

Existing list generation methods like range can be used as the existing list. Other data structures based on lists (like Sets) can also be used as an existing list.


Example
#generate a list with values from 0 to 10
zero_to_ten = [x for x in range(11)]

#generate a list with values from 0 to 100, real quick
zero_to_a_hundred = [x*10 for x in zero_to_ten]

See Also
Related

Lists

Documentation

5. Data Structures -- Python Documentation

Add to Slack

< Lists   |   Tuples >

© 2018 SyntaxDB. All Rights Reserved.