Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views1 page

Python 1

This document is a Python cheat sheet covering various data structures including tuples, lists, dictionaries, and sets. It provides syntax examples for creating and manipulating these data types, along with notes on their properties and common operations. Additionally, it includes information on Python's scalar types and module usage.

Uploaded by

kameshwaran.s
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)
10 views1 page

Python 1

This document is a Python cheat sheet covering various data structures including tuples, lists, dictionaries, and sets. It provides syntax examples for creating and manipulating these data types, along with notes on their properties and common operations. Additionally, it includes information on Python's scalar types and module usage.

Uploaded by

kameshwaran.s
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/ 1

Data Structures

Python Cheat Sheet Create Tuple tup1 = 4, 5, 6 or


tup1 = (6,7,8)

Note :
• 'start' index is included, but 'stop' index is NOT.
just the basics Create Nested Tuple tup1 = (4,5,6), (7,8)
• start/stop can be omitted in which they default to
Convert Sequence or tuple([1, 0, 2]) the start/end.
Iterator to Tuple
Created By: Arianne Colton and Sean Chen Concatenate Tuples tup1 + tup2
Unpack Tuple a, b, c = tup1 § Application of 'step' :
Application of Tuple Take every other element list1[::2]

General Scalar Types Swap variables b, a = a, b Reverse a string str1[::-1]

LIST DICT (HASH MAP)


• Python is case sensitive
* str(), bool(), int() and float() are also explicit type One dimensional, variable length, mutable (i.e.
• Python index starts from 0 cast functions. contents can be modified) sequence of Python objects Create Dict dict1 = {'key1' :'value1', 2
of ANY type. :[3, 2]}
• Python uses whitespace (tabs or spaces) to indent
5. NoneType(None) - Python 'null' value (ONLY Create Dict from dict(zip(keyList,
code instead of using braces. list1 = [1, 'a', 3] or Sequence valueList))
one instance of None object exists) Create List list1 = list(tup1)
HELP • None is not a reserved keyword but rather a Get/Set/Insert Element dict1['key1']*
list1 + list2 or dict1['key1'] = 'newValue'
unique instance of 'NoneType' Concatenate Lists* list1.extend(list2) dict1.get('key1',
Help Home Page help() Get with Default Value defaultValue) **
• None is common default value for optional Append to End of List list1.append('b')
Function Help help(str.replace) function arguments : Insert to Specific list1.insert(posIdx, Check if Key Exists 'key1' in dict1
Module Help help(re) Position 'b') ** Delete Element del dict1['key1']
def func1(a, b, c = None) valueAtIdx = list1. Get Key List dict1.keys() ***
Inverse of Insert pop(posIdx)
MODULE (AKA LIBRARY) • Common usage of None : Remove First Value list1.remove('a')
Get Value List dict1.values() ***
from List dict1.update(dict2)
Python module is simply a '.py' file Update Values
if variable is None : Check Membership 3 in list1 => True *** # dict1 values are replaced by dict2
List Module Contents dir(module1)
Sort List list1.sort()
Load Module import module1 * 6. datetime - built-in python 'datetime' module * 'KeyError' exception if the key does not exist.
Sort with User- list1.sort(key = len)
provides 'datetime', 'date', 'time' types.
Call Function from Module module1.func1() Supplied Function # sort by length ** 'get()' by default (aka no 'defaultValue') will
• 'datetime' combines information stored in 'date'
and 'time' return 'None' if the key does not exist.
* import statement creates a new namespace and * List concatenation using '+' is expensive since
executes all the statements in the associated .py a new list must be created and objects copied *** Returns the lists of keys and values in the same
dt1 = datetime.
file within that namespace. If you want to load the Create datetime strptime('20091031', over. Thus, extend() is preferable. order. However, the order is not any particular
module's content into current namespace, use 'from from String '%Y%m%d') order, aka it is most likely not sorted.
module1 import * ' ** Insert is computationally expensive compared
Get 'date' object dt1.date() with append. Valid dict key types
Get 'time' object dt1.time() • Keys have to be immutable like scalar types (int,
*** Checking that a list contains a value is lot slower
float, string) or tuples (all the objects in the tuple
Scalar Types Format datetime dt1.strftime('%m/%d/%Y
to String %H:%M')
than dicts and sets as Python makes a linear
scan where others (based on hash tables) in need to be immutable too)
Change Field dt2 = dt1.replace(minute = constant time. • The technical term here is 'hashability',
Check data type : type(variable) Value 0, second = 30) check whether an object is hashable with the
diff = dt1 - dt2 hash('this is string'), hash([1, 2])
Get Difference Built-in 'bisect module‡
SIX COMMONLY USED DATA TYPES # diff is a 'datetime.timedelta' object
• Implements binary search and insertion into a
- this would fail.
1. int/long* - Large int automatically converts to long Note : Most objects in Python are mutable except sorted list SET
2. float* - 64 bits, there is no 'double' type for 'strings' and 'tuples' • 'bisect.bisect' finds the location, where 'bisect. • A set is an unordered collection of UNIQUE
insort' actually inserts into that location. elements.
3. bool* - True or False
4. str* - ASCII valued in Python 2.x and Unicode in Python 3 ‡ WARNING : bisect module functions do not • You can think of them like dicts but keys only.
• String can be in single/double/triple quotes Data Structures check whether the list is sorted, doing so would
be computationally expensive. Thus, using them Create Set set([3, 6, 3]) or
{3, 6, 3}
• String is a sequence of characters, thus can be in an unsorted list will succeed without error but
Test Subset set1.issubset (set2)
treated like other sequences may lead to incorrect results.
Note : All non-Get function call i.e. list1.sort() Test Superset set1.issuperset (set2)
• Special character can be done via \ or preface examples below are in-place (without creating a new
with r SLICING FOR SEQUENCE TYPES† Test sets have same set1 == set2
object) operations unless noted otherwise. content
str1 = r'this\f?ff' † Sequence types include 'str', 'array', 'tuple', 'list', etc. • Set operations :
• String formatting can be done in a number of ways TUPLE Union(aka 'or') set1 | set2
One dimensional, fixed-length, immutable sequence Notation list1[start:stop] Intersection (aka 'and') set1 & set2
template = '%.2f %s haha $%d';
str1 = template % (4.88, 'hola', 2) of Python objects of ANY type. list1[start:stop:step] Difference set1 - set2
(If step is used) § Symmetric Difference (aka 'xor') set1 ^ set2

You might also like