python comprehensions
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Expression
The expression is the current item in the iteration, but it is also the outcome
Example
Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
1 | fruits=["apple","banana","cherry","kiwi","mango"] |
Two-dimensional array
Before that we should create one-dimensional array firstly.
1 | arr1=[0 for x in range(10)] |
Now, we can create two-dimensional arrays based on one-dimensional arrays.
1 | arr1=[[0 for x in range(10)] for x in range(2)] |
