0% found this document useful (0 votes)
22 views

Summary Python

This document provides a cheat sheet summarizing common Python concepts including: - Lists, strings, tuples, and dictionaries and their associated methods. - Built-in functions such as print(), len(), range(), etc. - Flow control statements like if/else and loops like for and while. - Functions, lambda expressions, and modules/imports. - Other concepts covered include type conversion, immutability, and list comprehensions.

Uploaded by

janespenico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Summary Python

This document provides a cheat sheet summarizing common Python concepts including: - Lists, strings, tuples, and dictionaries and their associated methods. - Built-in functions such as print(), len(), range(), etc. - Flow control statements like if/else and loops like for and while. - Functions, lambda expressions, and modules/imports. - Other concepts covered include type conversion, immutability, and list comprehensions.

Uploaded by

janespenico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PYTHON CHEAT SHEET

LISTS BUILT-IN FUNCTIONS


list1.append(‘a’) Add the ‘a‛ element at the end of the list print(“hi”) Print at the standard output
list1.extend([‘a’,’b’]) Add 'a’ and ‘b’ elements at the end of the list print var1
list1.insert(i,’c’) Insert the ‘c’ element at the i position. print “variable 1 %d” %var1
Attention! the position must exist print “variable1: ”, var1
list1.remove(‘a’) Remove the first appearance of the ‘a’ element type(var1) Returns the type of the object (integer, float, etc.)
list1.pop([i]) Return and delete the element at the i position.
len(lista1) Length of a sequence (lists and strings)
If i is not indicated, i = the last element
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list1.index(‘a’) Return the index of the first element
matching ‘a’. Attention! ‘a’ must exist! xrange(0, 10) The same as range but faster
list1.count(’a’) Return the number of times that ‘a’ appears in id(var) Memory identifier of the object
the list int(), float(), list(), dict(), etc. Type conversion
list1.sort() Sort the list max(lista1), min(lista1) Returns the maximum or minimum of a list
list1.reverse() Invert the order of the list zip([10, 11, 12], [20, 21, 22]) Returns [(10, 20), (11, 21), (12, 22)]
map(func, list1) Calls func() function using the elements of list1 as
arguments
reduce(func(a, b), list1) Calls func(a, b) function, being ‘a’ the cumulated value
STRINGS
and ‘b’ the current element of list1
string1.capitalize() Copy of the string with the first
filter(func(a), lista1) Add the elements for which func(a) returns True
position in capital letters
for i, j in enumerate([10, 11, 12]): i, j = 0, 10; 1, 11; 2, 12
string1.count(‘ab’) Number of times that the ‘ab‛
sorted(list1) Returns a new object corresponding to list1 once
sub-string appears
sorted
string1.find(‘ab’) Index of the first position
input() Introduction of values using the keyboard
where the ‘ab‛ sub-string appears
raw_input() Introduction of values using the keyboard.
string1.replace(‘old’,’new’) Replace the ‘old’ sub-string
Attention! everything is considered as a string
with the ‘new' sub-string
dir(object) Returns a list with all object methods
string1.split(‘del’) Divide the string according
to the delimiter. Attention! TUPLES
returns a list
tuple1.count(‘a’) Counts the number of times that ‘a’ appears in the tuple
string1.join([‘cad1’, ‘cad2’]) Concatenate cad1 and cad2 Returns the index of the first appearance of ‘a’.
tuple1.index(‘a’)
at the end of string1 Attention! the tuple must contain an ‘a’ element.
string1.strip() Delete the blank spaces at the
beginning and at the end of string1
PYTHON CHEAT SHEET

DICTIONARIES
dict.items() Returns a list with the format [(key1,
value1), (key2, value2),…]
dict.keys() Returns the list of the keys
dict.values() Returns the list of the values
dict.copy() Copy of the dictionary, they do not point
the same memory address
dict.pop(key1) Delete the key1-value1 pair.
Attention! key1 must exist!
dict.clear() Delete all elements of the
dictionary

LOOPS
for i in sequence:
# body of the loop!
# i gets the values of the sequence!
# do not forget tabs!
# do not forget the colon!
# Sequences are lists and strings!
# Here the loop ends
while condition:
# body of the loop!
# do not forget tabs and colons!
# Here the loop ends
break Get out of the loop
continue Jump to the next
iteration
pass It does not do anything
List comprenhension:
[x*x for i in [1, 2, 3, 4]] FUNCTIONS
FLOW CONTROL
Result: Def func_name(var1, var2):
If condition:
[1, 4, 9, 16] “”” Docstring
# if the condition is satisfied, Attention to tabs!
“””
else:
# Body of the function!
# if the condition is not satisfied, Attention to tabs!
# Do not forget tabs!
# Do not forget colon
IMPORT LIBRARIES/MODULES return result # optional
import random random.uniform(0, 10) lambda x: x * x
import random as rd rd.uniform(0, 10)
from random import uniform uniform(0, 10) #Attention! only MUTABILITY
uniform is available, the rest of Integers Immutable
methods/objects are not Float Immutable
from random import* uniform(0, 10) # Every Boolean Immutable
method is available Lists Mutable
Tuples Immutable
Dictionaries Mutable

PYTHON CHEAT SHEET

FILE MANAGEMENT
File = open(“myfile.txt”, 'r') Open myfile.txt file as read-only
File = open(“myfile.txt”, 'w') Open myfile.txt file as editable
File.close() Close file both as read-only and editable
File.write(str1) Write str1 to the file.
File.readlines() Returns a list that contains all lines of the file

for line in File: Go through all lines of the file. Work with line variable
PYTHON CHEAT SHEET
CLASSES
class myclass (object):
“””Docstring
“””
def __init__(self,atr1, atr2):
# Here the builder begins
self.atr1 = atr1
self.atr2 = atr2
def method1(self):
MAGIC FUNCTIONS # body of method1
return (self.atr1 + 2)
%clear Clear the terminal, not the objects
%exit Delete the objects def method2(self):
# body of method2
%run file1.py Run the script
Obj1 = myclass(10, 20) Define and initialize
%history Command history
the object
%cd “folder” Switch to the folder directory
Obj1.atr1 Access to the
%”command”? Help
attributes
PIP
Obj1.method1() Access to the
!pip install module Install module/library
methods
!pip upgrade module Upgrade module/library
!pip show version Show version of module/library

SLICING
sequence[0] First element
sequence[-1] Last element
sequence[:] All elements
sequence[a:b] Elements within the [a, b) interval
sequence[a:b:p] Elements within the [a, b) interval
with p step

You might also like