Physical & Logical New Lines in Python with Examples

In lexical analysis, python program is processed by parser. Parser takes token of streams generated by lexical analyzer as input. To understand how tokens are generated from python file we must understand physical and logical new lines in python.

This article explains line structure, Physical & Logical, in python with types, their differences and examples.

New Line Structure

Python program is divided into number of logical lines while python source code is divided into number of physical as well as logical lines.

Logical Lines

Logical lines of code ends with logical NEWLINE token. This token is generated by lexical analyzer before parsing.

Logical Newline Example

Consider a following python code:

number_list = [1,2,3,4,5,6]

This code has One Logical Line.

Physical Lines

Physical lines of code ends with a physical newline character. Sometimes, physical newlines are ignored in order to combine multiple physical lines into a single logical line of code.

Physical Newline Example

The code in the logical newline example can also be written as:

number_list = [1,

This program has Five Physical Lines but One Logical Lines.