Python 3 Basic Syntax

The basic syntax to learn before writing code in Python 3.


I occasionally write scripts in Python 3 and this article keeps track of basic syntax that is frequently used according to my experience. To keep things simple, this article is focus on language syntax and does not include framework or tooling of the Python ecosystem. Code written here is tested and hosted on GitHub. I hope that it will be useful for you as well. Enjoy!

Data Container

This section discusses about list, set, and dictionary.

Container Creation

Create a dictionary, list, set:

import typing

# dictionary
my_dict1 = {"k1": "v1", "k2": "v2", "k3": "v3"}
my_dict2 = dict()
my_dict3 = typing.OrderedDict()

# list
my_list1 = ["v1", "v2", "v3"]
my_list2 = list()
my_list3 = [0] * 4  # [0, 0, 0, 0]

# set
my_set1 = {"k1", "k2", "k3"}
my_set2 = set()

Container Iteration

Iterate keys of a dictionary:

for key in my_dict:

Iterate values of a dictionary:

for value in my_dict.values():

Iterate key-value pairs of a dictionary:

for key, value in my_dict.items():
    print(key, value)

Iterate item in a list:

for item in my_list:

Iterate index and item in a list:

for i, item in enumerate(my_list):
    print(i, item)

List Comprehension

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

new_list = [ expression(element) for element in old_list if condition ]


>>> my_dict = {'k1': 'v1', 'k2': 'v2'}

>>> [v for v in my_dict.values()]
['v1', 'v2']

>>> [k for k in my_dict]
['k1', 'k2']

>>> [k for k in my_dict if k == 'k1']

>>> [k + ':' + v for k, v in my_dict.items()]
['k1:v1', 'k2:v2']

Container Insertion

Append an element into list or replace an existing element:

my_list[1] = e

Add an element into set:


Add a new entry into dictionary or increment an existing value:

my_dict["my_key"] = 2
my_dict["my_key] += 1

Container Functions

Function Sample Description
len len(my_list) The length of the container.
enumerate enumerate(my_list) Add counter to the iterable.
max max(my_list) The maximal value among the given items.
min min(my_list) The minimal value among the given items.
reversed reversed(my_list) Create a reverse-iterator for a given list.

If Statement

Ternary operator:

TrueExpression if Condition else FalseExpression
>>> l = []
>>> 'not empty' if l else 'empty'


Function Sample Description
Floor division, integer division (//) 7 // 2 3
Float division (/) 7 / 2 3.5


class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name): = name    # instance variable unique to each instance

String Manipulations

Hint: hit TAB in Python REPL to see auto-completion for the string functions.

Category Function Description
Whitespace strip() Trim the string
Whitespace lstrip() Left trim
Whitespace rstrip() Right trim
Case lower() Lower case
Case upper() Uppder case
Split split(), split(sep) Split the string using whitespace or a seperator
Cancatenation join(words) Join words together using a given string