Python comprehension

Background

When I was solving the ATcoder sample problem, the processing time limit could not be exceeded. I solved it by using the comprehension notation, so I will summarize it so that I do not forget it

syntax

[String for variables in list or list]

By writing a conditional expression after the range, it is possible to list only those that apply to the conditional expression.

Example)

//Expected results=>[0,2,4,6,8,10]
l = [i for i in range(11) if i%2 == 0]
print(l)
//[0,2,4,6,8,10]

The conditional expression can be put in the for statement, or the value extracted in the for statement can be multiplied by the conditional expression.

//Expected results=>['Apple','Grapes','Apple','Grapes','Apple','Grapes']
l = ['Apple' if i%2 == 1 else 'Grapes' for i in range(11)]
print(l)
//['Apple', 'Grapes', 'Apple', 'Grapes', 'Apple', 'Grapes']

Situations to use

Basically, when creating a list, use it when you want to make the processing speed faster than using it in append.

Since it can support not only lists but also dictionaries and binary arrays, it can be used for code simplification when processing long arrays, so it should be used.

Recommended Posts

Python comprehension
Python comprehension
About python comprehension
Python> Comprehension / Comprehension> List comprehension
Python Exercise 2 --List Comprehension
Python
Python list comprehension speed
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
List comprehension
python tips
Comprehension notation
python function ①
Python basics
Python memo
ufo-> python (3)
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Set comprehension
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
List comprehension
Python update (2.6-> 2.7)
python memo
Python memorandum