0% found this document useful (0 votes)
5 views4 pages

All The Python Language Features You Need - DeriveIt

This document provides a comprehensive overview of essential Python language features, including built-in types, basic operations, loops, list comprehensions, generator comprehensions, and functions. It also covers string manipulation, casting between types, and the use of anonymous functions. Additionally, it offers practical examples and syntax for various Python constructs, making it a useful cheat sheet for Python programming.

Uploaded by

qz2bpxvjbr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

All The Python Language Features You Need - DeriveIt

This document provides a comprehensive overview of essential Python language features, including built-in types, basic operations, loops, list comprehensions, generator comprehensions, and functions. It also covers string manipulation, casting between types, and the use of anonymous functions. Additionally, it offers practical examples and syntax for various Python constructs, making it a useful cheat sheet for Python programming.

Uploaded by

qz2bpxvjbr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

2/12/24, 12:15 PM All the Python Language Features You Need - DeriveIt

Cheat Sheets

All the Python Language Features You Need


CONCEPT

Here are all the import Python language features you need to know. You can read the official Python docs too - we recommend
skimming the Built-in Functions and Built-in Types sections.

https://leetcode.com/playground/new is a good place to run code if you ever want to try anything out. Use Python3.

Built-in Types
x = "123" # string
x = 1 # integer
x = 1.0 # float
None # null
True # true
False # false

x = [1, 2, 3] # list (Array)


x = {1: "a"} # dict (HashMap)
x = {1, 2, 3} # set
x = (1, 2, 3) # tuple (Immutable array)

Basic Operations
x and y # and
x or y # or

1 % 2 # 1 (mod)
1 / 2 # .5 (division)
1 // 2 # 0 (division, rounding down)
2 ** 5 # 32 (power, 2^5)

x if condition else y # if the condition holds give x, otherwise give y

a == b # compare by value
a is b # compare by memory location (exact comparison)

any([True, False, False]) # True if any value holds, False otherwise


all([True, False, False]) # True if all values hold, False otherwise

float('inf') # +infinity
float('-inf') # -infinity

[a, b] = [1, 2] # destructuring (set a=1, b=2)


(a, b) = (1, 2) # destructuring (set a=1, b=2)
a, b = 1, 2 # destructuring ("x,y" always gets interpreted as (x,y))

Loops and range


for x in range(20): # 0...19
https://deriveit.org/coding/cheat-sheets/118 1/4
2/12/24, 12:15 PM All the Python Language Features You Need - DeriveIt
g ( )
# ...

for x in range(20, 30): # 20...29


# ...

for x in range(20, 30, 2): # 20...29 in steps of 2 (20, 22, 24, 26, 28)
# ...

for x in range(n-1, -1, -1) # iterate backwards from n-1...0


# ...

for x in ["a", "b", "c"]: # iterate through "a", "b", "c"


# ...

while x < 20:


# ...

List Comprehensions
Python has nice syntax for creating Arrays. Here's an example:

x = [2*n for n in range(5)]


# [0, 2, 4, 6, 8]

You can take this pretty far:

x = [(row, col) for row in range(2) for col in range(2)]


# [(0,0), (0,1), (1,0), (1,1)]

x = [[row+col for col in range(4)] for row in range(3)]


# [[0,1,2,3], [1,2,3,4], [2,3,4,5]]

x = [a for a in [1,2,3,4,5,6] if a % 2 == 0]
# [2,4,6]

Here's an example that shows you what list comprehension is actually doing:

x = [a*b for a in A for b in B if a > 5]


# Is equivalent to:
x = []
for a in A:
for b in B:
if a > 5:
x.append(a*b)

Generator Comprehensions
List comprehensions always run the entire for-loop (above). Generator comprehensions generate values lazily, and can stop early. To do
a generator comprehension, just use () instead of [] .

# stops early if finds True, without executing all 20 expensive computations


any(expensiveComputation(a) for a in range(20))

computations = (expensiveComputation(a) for a in range(20)) # <-- computes nothing here. The loop only run
when we read from the `computations` variable

# this might stop early, without executing all 20 expensive computations:


for x in computations:
...
if done: break

Note that () can mean a tuple, or it can mean a generator. If you use them like this it means a generator.

https://deriveit.org/coding/cheat-sheets/118 2/4
2/12/24, 12:15 PM All the Python Language Features You Need - DeriveIt
If you're curious how generator comprehensions work internally, instead of running x.append(...) above, they just run yield ...
(it's ok if you don't know about yield).

List Features
x = [1,2,3] + [4,5,6] # [1,2,3,4,5,6]
x = [0, 7] * 10 # [0,7,0,7,0,7,0,7,0,7,0,7,0,7,0,7,0,7,0,7,0,7]

x = [0,1,2,3,4]
x[-1] # 4
x[3:] # [3,4]
x[:3] # [0,1,2] (start=0, stop=3 exclusive)
x[1:4] # [1,2,3]
x[4:0:-1] # [4,3,2,1] (start=4, stop=0 exclusive, step=-1)

# To create an m x n matrix of zeros, do this:


x = [[0 for col in range(n)] for row in range(m)]

y = reversed(x) # reversed array of x


x.reverse() # reverses x in-place using no extra memory
sorted(x) # sorted array of x
x.sort() # sorts x in-place using no extra memory

See Matrix with One for more details about [x]*n syntax, and why you shouldn't use it to build a 2D array.

Set Features
DeriveIt
x = {"a", "b", "c"} Log In
y = {"c", "d", "e"}
y = x | y # merge sets, creating a new set {"a", "b", "c", "d", "e"}

String Features
x = 'abcde' # you can use '' or "" for strings (it doesn't matter which)
y = "abcde"
y[2] # gives "c"
z = x + y # concatenate strings

# iterate through every letter in y:


for letter in y:
# ...

Functions
You declare a function using the def keyword:

def my_function():
# do things here

All variables you declare inside a function in Python are local. In most cases you need to use nonlocal if you want to set variables
outside a function, like below with x and y .

# initialize x,y,z to 100


x = 100
y = 100
z = [100]

# set x,y,z to 1 inside the function


def myfuntion():
nonlocal y # tells computer to refer to global variable `y`
x = 1 # `x` is local
y = 1 # `y` is global
[0] th l b l ` ` b th lt ti i t th
https://deriveit.org/coding/cheat-sheets/118 3/4
2/12/24, 12:15 PM All the Python Language Features You Need - DeriveIt
z[0] = 1 # Python uses global `z` because the alternative is to throw an error

myfunction()

x # 100
y # 1
z[0] # 1

Anonymous Functions
You can also declare a function in-line, using the keyword lambda . This is just for convenience. It's useful when you want to pass a
function as a parameter and you don't care about naming it. These two statements both create the same function:

def fn(x,y):
return x + y

lambda x,y: x + y

Casting
You can convert between primitive types like this:

x = [1, 2, 3, 4]
s = set(x) # converts x to a set
t = tuple(x) # converts x to a tuple
l = list(s) # converts s to a list (order might not be the same as x because sets don't store order)

n = 7
s = str(n) # converts n to a string, '7'
z = int(s) # converts s to a number again, 7

Newlines
You can write something on multiple lines by escaping the newline like this:

x = 5 \
+ 10 \
+ 6

Mark as Completed:

Next
Concept

Terms About Feedback Contact Us

https://deriveit.org/coding/cheat-sheets/118 4/4

You might also like