Skip to content

lifeparticle/Python-Cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

92 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

contributions welcome

Table of Contents

Installation

How to install python

If you don't want to install python natively you can use docker.

docker run -it --rm python:latest
# check which version of python you're running
python --version

Comment

# single line comment

# begin
# multiline
# comment
# end

or

"""
begin
multiline
comment
end
"""

Operators

Logical operators

No operator
1 and
2 or
3 not
4 &&
5 ||
6 !

Bitwise operators

No operator
1 &
2 |
3 ^
4 ~
5 <<
6 >>

Arithmetic operators

No operator
1 +
2 -
3 *
4 /
5 %
6 **
7 //

Comparison operators

No operator
1 ==
2 !=
3 >
4 <
5 >=
6 <=
7 <>

Assignment operators

No operator
1 =
2 +=
3 -=
4 *=
5 /=
6 %=
7 **=
8 //=

Conditional structures

x = 11
if x > 10:
    print("The number is greater than 10")
else:
    print("The number is not greater than 10")
if x == 10:
    print('The value of x is 10')
elif x == 11:
    print('The value of x is 11')
else:
    print('The value of x is not either 10 or 11')

Ternary Operators

execute_if_true if condition else execute_if_false
print "even" if 6 % 2 == 0 else "odd"

# output
# even

Data types

No Type Example Class Type
1 int > a = 17 > a.__class__.__name__
> 'int'
Numeric Types
2 float > a = 87.23 > a.__class__.__name__
> 'float'
Numeric Types
3 complex > a = 1j or > a = 1J > `a.class.name``
> 'complex'
Numeric Types
4 str > a = "Hello universe" > a.__class__.__name__
> 'str'
Text Sequence Type
5 list > a = ["a", "b", "c"] > a.__class__.__name__
> 'list'
Sequence Types
6 tuple > a = ("a", "b", "c") > a.__class__.__name__
> 'tuple'
Sequence Types
7 range > a = range(7) > a.__class__.__name__
> 'range'
Sequence Types
8 dict > a = {"name" : "Tom", "age" : 17} > a.__class__.__name__
> 'dict'
Mapping Types
9 set > a = {"a", "b", "c"} > a.__class__.__name__
> 'set'
Set Types
10 frozenset > a = frozenset({"a", "b", "c"}) > a.__class__.__name__
> 'frozenset'
Set Types
11 bool > a = True > a.__class__.__name__
> 'bool'
Boolean Types
12 bytes > a = b"Hello universe" > a.__class__.__name__
> 'bytes'
Binary Sequence Types
13 bytearray > a = bytearray(7) > a.__class__.__name__
> 'bytearray'
Binary Sequence Types
14 memoryview > a = memoryview(bytes(7)) > a.__class__.__name__
> 'memoryview'
Binary Sequence Types

Further readings

How to check data type

a = 37
isinstance(a, int)
# True
isinstance(a, float)
# False
type(10)
# <type 'int'>

String

print('Hello World'[0])
# H
print('Hello World'[1])
# e

List

a = ["a", "b", "c"]

f, s, t = ["a", "b", "c"]
# output
# f = 'a'
# s = 'b'
# t = 'c'

f, *mid, l = ["a", "b", "c"]

# output
# f = 'a'
# mid = ['b']
# l = 'c'
a = ["a", "b", "c"]
b = ["d", "e", "f"]

a.append(b)
# output
# ['a', 'b', 'c', ['d', 'e', 'f']]

a = ["a", "b", "c"]
b = ["d", "e", "f"]

a.extend(b)
# output
# ['a', 'b', 'c', 'd', 'e', 'f']

List slice

list[start_index:stop_index:step]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[0::2]

# output
# [1, 3, 5, 7, 9]


numbers[1::2]

# output
# [2, 4, 6, 8, 10]

List Comprehensions

Create a list of lists

[[0]*2 for i in range(2)]

# output
# [[0, 0], [0, 0]]

Create a list of variable length of lists

n = 10
[[0]*(i+1) for i in range(n)] + [[0]*i for i in range(n-1, 0, -1)]

# output
# [[0],
# [0, 0],
# [0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0],
# [0, 0],
# [0]]

Create a matrix of multiplication tables

n = 5
[[i*j for i in range(1,n+1)] for j in range(1, n+1)]

# output
# [[1, 2, 3, 4, 5],
# [2, 4, 6, 8, 10],
# [3, 6, 9, 12, 15],
# [4, 8, 12, 16, 20],
# [5, 10, 15, 20, 25]]

Dictionary

Dictionary Comprehensions

{c: ord(c) - 96 for c in string.ascii_lowercase[:26]}

# output
# {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}

Set

Set Comprehensions

numbers = [2, 2, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14]
uniqueEvenNumbers = {num for num in numbers if num % 2 == 0}

# output
# set([2, 4, 6, 8, 10, 12, 14])

uniqueNumbers = set(numbers)

# output
# set([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

map() Function

map(function, list)
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda n: n*n, numbers))

# output
# [1, 4, 9, 16, 25]

filter() Function

filter(function, list)
numbers = [1, 2, 3, 4, 5]
odd = list(filter(lambda n: n % 2 != 0, numbers))

# output
# [1, 3, 5]

reduce() Function

reduce(function, list)
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers

# output
# 15

zip() Function

Creates an iterator of tuples.

zip(iterator1, iterator2, iterator3 ...)
a = ['a', 'b', 'c']
b = [1, 2, 3]

zip(a, b)

# output
# [('a', 1), ('b', 2), ('c', 3)]

tuples to list

list(map(list, zip(a, b)))

# output
# [['a', 1], ['b', 2], ['c', 3]]

format() function

"{:{width}.{prec}f}".format(10.344, width=10, prec=6)

# output
# ' 10.344000'

Miscellaneous

Get the number of bits in an integer in binary, excluding the sign and leading zeros.

n.bit_length()

Swap two variables in one line

a, b = b, a

My Python Articles

  1. How To Run a Python Script Using a Docker Container
  2. How To Create a Twitter Bot in Python
  3. How To Extract Text From Images Using Tesseract OCR Engine and Python
  4. How to Connect to a PostgreSQL Database With a Python Serverless Function
  5. How to Deploy a Python Serverless Function to Vercel
  6. How to Dockerize an Existing Flask Application
  7. How To Create a Docker Image From a Container

Books and other resources

  1. TODO

Bug Reports and Feature Requests

Please create an issue with as much information you can. Thank you.

Author

Mahbub Zaman (https://mahbub.ninja)

License

MIT License

Releases

No releases published

Sponsor this project

 

Packages

No packages published