Cheat Sheet: Writing Python 2-3 compatible code. Essential syntax differences. # Python 2 and 3: # To make Py2 code safer (more like Py3) by preventing # implicit relative imports, you can also add this to the top: from future import absoluteimport. I occasionally write Python scripts, but I always forget those very basic syntax. So I’m writing this Python 3 cheat sheet.
In this Tutorial You will learn about python in detail . In this period python is mostly used. Python is a precious programming language. It is easy to learn, and its syntax is too much simple.Most of People think about how to Learn python. Python is important for beginners. In this tutorial You will Learn complete python Via Chat sheet
- Python is a beautiful language. It's easy to learn and fun, and its syntax is simple yet elegant. Python is a popular choice for beginners, yet still powerful enough to. Python Cheat Sheet 1. Primitives Numbers. In the above example, pi is the variable name, while 3.14 is the value.
- Python Strings cheat sheet of all shortcuts and commands. Partition string at sep and return 3-tuple with part before, the sep itself, and part after # 'hello.
- ©2012-2015 - Laurent Pointal Python 3 Cheat Sheet License Creative Commons Attribution 4 Latest version on.5 -4 -3 -2 -1 Individual access to items via lstindex.
You can Download Free python Cheat sheet PDF.
1. Primitives: |
In this example, pi is the variable name, while 3.14 is the value.
Strings |
Boolean’s: |
2. Collections |
Dictionaries:- |
IF Statements:- |
Table of Contents
- Built-in Types
- Sequence Types
- Dictionaries
- Lists
- Strings
- Iterators
- Functional Iteration
- Decorators
- Generators
- Other Useful Built-in Functions
- Common Gotchas
Built-in Types
In this section I have included information on the more basic built-in types. For information on more specialized built-in types, check out the Python documentation
Boolean Types
By default, an object is considered True
unless its class defines either a __bool__()
method that returns False
or a __len__()
method that returns zero. Here are most of the built-in objects considered False
:
- constants defined to be false:
None
andFalse
- zero of any numeric type:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- empty sequences and collections:
'
,()
,[]
,{}
,set()
,range(0)
Python 3.7 Cheat Sheet Pdf
Numeric Types
Integers have unlimited precision. Floating point numbers are usually implemented using double
in C, and are therefore system-dependent. Complex numbers have a real and imaginary part, which can be accessed using z.real
and z.imag
, respectively. Complex numbers must include j
appended to a numeric literal (0j
is acceptable for when you want a complex
value with no imaginary part).
The standard libarary includes additional numeric types, Fractions which hold rationals, and Decimals which hold floating-point numbers with user-definable precision.
Sequence Types
Immutable sequences have support for the hash()
built-in, while mutable sequences do not. This means that immutable sequences can be used as dict
keys or stored in set
and frozenset
instances, while mutable sequences cannot.
Mutable Sequences
bytearray
objects are a mutable counterpart to bytes
objects.
Immutable Sequences
bytes
objects are sequences of single bytes. The syntax for bytes
literals is largely the same as that for string literals, except that a b
prefix is added:
- Single quotes:
b'still allows embedded 'double' quotes'
- Double quotes:
b'still allows embedded 'single' quotes'
- Triple quotes:
b''3 single quotes''
,b''3 double quotes''
Only ASCII chars are permitted in bytes
literals.bytes
objects actually behave like immutable sequences of integers, with each value restricted to 0 <= x < 256
.
bytes
objects can be created in several ways:
- A zero-filled bytes object of a specific length:
bytes(10)
- From an iterable of integers:
bytes(range(20))
- Copying existing binary data via the buffer protocol:
bytes(obj)
Set Types
set
is mutable, while frozenset
is immutable.
Note that since frozenset
is immutable, it must be entirely populated at the moment of construction. It cannot use the literal curly brace syntax that ordinary set
uses, as that syntax is reserved for set
.
Instead, use frozenset([iterable])
.
Mapping Types
See the Dictionaries section for more info.
Dictionaries
Dictionary Iteration
Get w/ default value if key not in dict:
Iterating a dict iterates only the keys:
Testing membership: if k in dict: ...
To get actual key-value pairs at the same time:
applies to comprehensions as well: new_d = {k: v+1 for k,v in d.items()}
Dictionary Sorting
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
sorted(d.items())
- sorted list of key-value pairs by key
- by value:
sorted(d.items(), key=lambda x: x[1]
sorted(d)
- sorted list of keys only
- sorted list of keys by value:
sorted(d, key=lambda x: d[x])
Lists
List Comprehensions
General Syntax:
is equivalent to:
Note how the order of the for
and if
statements remains the same.For example,
is the same as
List Initialization
Can use comprehensions:
2-D list (list of lists):
This is useful for a “visited” grid of some kind (common in Dynamic Programming problems):
BE CAREFUL when initializing a matrix.Do this:
NOT this:
The latter method makes copies of the reference to the original list, thus any modification to one row will change the other rows in the same way. The first method does not do this.
A list can be created from a string using list(my_str)
We can apply a filter as well:
List Reversal
my_list[::-1]
- returns copy of list in reverse
reversed(my_list)
- returns an iterator on the list in reverse
- can turn into a list via
list(reversed(my_list))
my_list.reverse()
- actually modifies the list
List Sorting
sorted(my_list)
- returns copy of sorted list
my_list.sort()
- actually modifies the list
By default, these methods will sort the list in ascending order. For descending order, we can supply the arg reverse=True
to either of the aforementioned methods.
We can also override the key for sorting by supplying the key
arg. For example, if we have a list of tuples and we want to use the second item as the key:
Additionally, if we want to sort in descending order:
When using sorted()
it works the same, except we supply the list as the first arg:
Strings
From List
String Constants
Python has a lot of useful string constants. A few of them are shown below.For a complete list, see the documentation
string.ascii_letters
string.digits
string.whitespace
e.g. if d in string.digits: ...
isalnum()
Returns True
if a string consists only of alphanumeric characters.
split()
Return a list of the words in the string, using sep
as the delimiter string. If maxsplit
is given, at most maxsplit
splits are done (thus, the list will have at most maxsplit + 1
elements). If maxsplit
is not specified or -1
, then there is no limit on the number of splits (all possible splits are made).
Usage:
strip()
Returns copy of string without surrounding whitespace, if any.
str()
vs repr()
See this GeeksForGeeks article for more info.
Iterators
In Python, an iterator is an object with a countable number of values that can be iterated upon.An iterator is an object which implements the iterator protocol, consisting of __iter__()
and __next__()
.
The __iter__()
method returns an iterator on the object, and the __next__()
method gets the next item using the iterator, or raises a StopIteration
exception if the end of the iterable is reached.
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.All these objects have a __iter__()
method which is used to get an iterator:
Note – next(obj)
is the same as obj.__next__()
.
How for loop actually works
The for
loop can iterate any iterable.
The for
loop in Python is actually implemented like so:
So, internally, the for
loop creates an iterator object by calling iter()
on the iterable, and then repeatedly calling next()
until a StopIteration
exception is raised.
Creating an Iterator
Here is an example of an iterator that will give us the next power of two in each iteration.
Now we can use it as follows:
Or, alternatively, using a for
loop:
Functional Iteration
For some good explanations and examples for the following functions, see here.
Note that map()
and filter()
both return iterators, so if you want a list, you need to use list()
on the output. However, this is typically better accomplished with list comprehensions or for
loops for the sake of readability.
map()
map()
applies a function to all the items in a list.
For example, the following code:
can be accomplished more easily with map()
:
filter()
filter()
creates a list of elements for which a function returns True
.
Here’s an example:
reduce()
reduce()
is used to perform a rolling computation on a list.
Here’s an example:
Often times, an explicit for
loop is more readable than using reduce()
.But if you’re trying to flex in an interview, and the problem calls for it, it could be a nice way to subtly show your understanding of functional programming.
Decorators
A decorator is a function returning another function, usually applied as a function transformation using the @wrapper
syntax. This syntax is merely syntactic sugar.
The following two function definitions are semantically equivalent:
@classmethod
Transform a method into a class method. A class method receives the class as implicit first argument, just like how an instance method receives the instance. To declare a class method:
A class method can be called either on the class (like C.f()
) or on an instance (like C().f()
). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Note that class methods are not the same as C++ or Java static methods. If you want those, see @staticmethod
.
@staticmethod
Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method:
A static method can be called either on the class (like C.f()
) or on an instance (like C().f()
). Static methods in Python are similar to those found in Java or C++.
@property
Return a property attribute.Usage:
fget
is a function for getting an attribute value. fset
is a function for setting an attribute value. fdel
is a function for deleting an attribute value. doc
creates a docstring for the attribute.
The following is a typical use case for defining a managed attribute x
:
Or, equivalently:
If c
is an instance of C
, then c.x
will invoke the getter; c.x = value
will invoke the setter; and del c.x
the deleter.
If doc
is not provided, the property will copy fget
’s docstring, if it exists. Thus, it is straightforward to create read-only properties with the @property
decorator:
The @property
decorator turns the voltage()
method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage
to “Get the current voltage.”
For more information, check out the documentation and this Programiz article.
Generators
Generators are simpler ways of creating iterators. The overhead of creating __iter__()
, __next__()
, raising StopIteration
, and keeping track of state can all be handled internally by a generator.
A generator is a function that returns an object (iterator) which we can iterate over, one value at a time.
Using yield
To create a generator, simply define a function using a yield
statement.
A function containing at least one yield
statement (it may contain other yield
and return
statements) becomes a generator.
Both yield
and return
return some value from a function. The difference is that, while a return
statement terminates a function entirely, yield
pauses the function, saving its state and continuing from where it left off in successive calls.
Once a function yields, it is paused and control is transferred back to the caller. Local variables and their states are remembered between successive calls. When the function terminates, StopIteration
is raised automatically on further calls.
Below is a simple generator example, for the sake of demonstrating how generators work.
Below is a more typical example. Generators often use loops with a suitable terminating condition.
Note that the above example works not just with strings, but also other kinds of iterables.
Generator Expressions
Generator expressions can be used to create an anonymous generator function. The syntax is similar to that of list comprehensions, but uses parentheses instead of square brackets. However, while a list comprehension produces the entire list, generator expressions produce one item at a time.
Generator expressions are kind of lazy, producing items only when asked for. For this reason, using a generator expression is much more memory efficient than an equivalent list comprehension.
Generator expressions can be used inside function calls. When used in such a way, the round parentheses can be dropped.
Other Useful Built-in Functions
For a complete list of built-ins in Python 3, see the documentation.
abs()
Returns the absolute value of a number, either an integer or floating point number.If the argument is a complex number, its magnitude is returned.
any()
Usage:
any()
takes any iterable as an argument and returns True
if at least one element of the iterable is True
.
See here for more info.
Check if any tuples contain a negative value:
all()
all()
takes any iterable as an argument and returns True
if all the elements of the iterable are True
.
See here for more info.
Check if all elements of a list are x
:
chr()
Returns the string representing a character whose Unicode code point is the integer passed.
For example, chr(97)
returns the string a
, while chr(8364)
returns the string €
.
This is the inverse of ord()
.
enumerate()
Usage:
Returns an enumerate object. iterable
must be a sequence, iterator, or some object which suports iteration. The __next__()
method of the iterator returned by enumerate()
returns a tuple containing a count (from start
which defaults to zero) and the values obtained from iterating over the iterable.
Example:
This is equivalent to:
input()
Gets input from the user.Usage:
Example:
If the prompt
arg is present, it is written to stdout without a trailing newline.
isinstance()
Usage:
Returns true if the object
argument is an instance of the classinfo
argument, or of a (direct, indirect, or virtual) subclass thereof. Returns false otherwise.
If classinfo
is a tuple of type objects, return true if object
is an instance of any of any of these types.
len()
Return the length of an object. The argument may be a sequence (e.g. string, bytes, tuple, list, or range) or a collection (e.g. dictionary, set, frozen set).
max()
Returns the max item in an iterable, or the max of multiple arguments passed.
min()
Returns the min item in an iterable, or the min of multiple arguments passed.
ord()
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
For example, ord('a')
returns the integer 97. ord('€')
(Euro sign) return 8364.
This is the inverse of chr()
.
pow()
Usage:
Return x
to the power y
; if z
is present, return x
to the power y
, modulo z
(computed more efficiently than pow(x, y) % z
).pow(x, y)
is equivalent to x**y
.
type()
Usage:
With one argument, return the type of object
. The return value is a type object and generally the same object as returned by object.__class__
.
E.g.
The isinstance()
function is recommended for testing the type of an object, since it accounts for subclasses.
Common Gotchas
Nested List Initialization
When creating a list of lists, be sure to use the following structure:
Read the section on list initialization to see why.
Mutable Default Arguments
Python 3.7 Cheat Sheet
If we try to do something like def f(x, arr=[])
this will most likely create undesirable behavior.Default arguments are resolved only once, when the function is first defined. The same arg will be used in successive function calls. In the case of a mutable type like a list, this means that changes made to the list in one call will be carried over in successive calls.Instead, consider doing: