0% found this document useful (0 votes)
158 views16 pages

C:/Users/Rafe/Appdata/Local/Programs/Python/Python35-32/Scripts Object and Data Structures Basics

This document contains information about various Python object and data structures like lists, dictionaries, tuples, files, sets, booleans, comparison operators, for loops, while loops, functions, classes, inheritance, special methods, and exceptions. It also discusses built-in functions like map, filter, reduce, enumerate, zip, modules, packages and decorators.

Uploaded by

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

C:/Users/Rafe/Appdata/Local/Programs/Python/Python35-32/Scripts Object and Data Structures Basics

This document contains information about various Python object and data structures like lists, dictionaries, tuples, files, sets, booleans, comparison operators, for loops, while loops, functions, classes, inheritance, special methods, and exceptions. It also discusses built-in functions like map, filter, reduce, enumerate, zip, modules, packages and decorators.

Uploaded by

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

C:\Users\rafe\AppData\Local\Programs\Python\Python35-32\Scripts

Object and Data Structures Basics


first_col = row[0] for row in lst

dictionaries

my_dict= {'k1' : 'dog', 'k2' : 42 }

my_dict[ 'k1' ]

my_dict['k2'] += 11

my_dict['k3'] = 'new' // add new tuple

d={'k1': {'nest': { 'subnest': 'value' }}}

d['k1']['nest']

d.keys()

d.values()

d.items()

tuples

t= (1,2,3)

t.length()

t= ('ocdc', 2)

t[0] t[-1]

t.index(‘one’) index of item

t.count(‘one’)

t[0]=’s’ Error. Immutability

files
Pwd gives loction of current working directory

f-open(‘test.txt’)

f.read()

f.read() Returns ‘ ’ as file already read

f.seek(0) takes to file starting

f.readlines() reads line by line

%%writefile new.txt

First line

Seocnd line

for line/words in open('new.txt')

print (line/words)

Sets and Booleans

Sets: unordered collection of unique elements

x=set()

x.add(2)

Set(listName) Gives unique elements in list

a=True

b=None Just a placeholder

b=’anything’

Comparison Operators

Python Statements
For Loops

l= [(2,4), (8,3), (4,9)]

for (t1, t2) in l:

print (t1)

d= {‘k1’: ‘gas’ , ‘k2’: 2 , ‘k3’: 3} prints keys only in unordered manner

for item in d:

print (item)

for k,v in d.iteritems(): use d.items() in python 3 to iterate through

print(k)

print (v)

While Loops

Break: Breaks out of current closest loop

Continue: goes to top of closest loop

Pass: does nothing at all

x=0

while x<10 :

print (‘x is currently: ’, x)

x +=1

if x==3:

print (‘x is 3’)

break

else:

print (‘continuing’)
continue

range

range(10)

start=0

end=11

range(start, end, 3)

Generators: allows generation of generated objects


but doesn’t store in memory

xrange() generator in python2.in python 3, range() is


generator itself

for num in xrange(1,100):

print (num)

xrange(1,10) Doesn’t print list

x=xrange(1,10) prints. type casting into list

list(x)

List Comprehensions

l=[] l= [letter for letter in ‘ice cream’]

for letter in ‘ice cream’

l.append(letter)

print(l)

lst = [x**2 for x in range(1,11)]

list= [numb for numb in range(11) if numb%2==0 ]

ls=[x**2 for x in [x**2 for x in range(11)]] gives x**4 for 1-10

Methods and Functions


l= [1,2,5]

help(l.count) // HELP info abount count method

Functions

def: built-in keyword. tells you are about to create a function //check python built-in functions

def is_prime(num):

“”” // docStirng

input: a number

output: prime or not

“””

for n in range(2, num)

if um%2==0

print (‘not prime’)

break

else:

print (‘prime’)

Lambda Expression

// create anonymous functions. body similar to what we would put in def body’s return statement.

// check ‘python conquers the universe’

def square(num): return num**2 // lamda num: num**2

square2 = lambda num: num**2

first= lamda s: s[0]


rev = lambda s: s[::-1]

adder = lambda x,y: x+y

Nested Statements and Scope

// a created variable name is stored in namespace

// Scopes: local enclosing function global built-in

x=50

def func():

global x

print (‘func is using the global x now’)

print (‘global x is ’, x)

x=2

print (‘func called, x is change now, x is: ’, x)

print (‘before calling func, x is: ’,x)

func()

print (‘x outside func: ’,x)

//use locals() and globals() function to check current local and global variables

// everything in python is an object

Object Oriented Programming


Objects

type(objectName) Ex: type({‘k1’:2}) type([1,2,3])

Everything is object in python


Classes

class Dog(object): init initializes object attribute. every method in a


class must have ‘self’ with it.
species= ‘mammal’

def __init__(self, breed, fur=True)

self.breed = breed

self.fur= fur

sam= Dog(breed= ‘lab’) // instance creation

sam.breed

sam.species

Methods

class Circle(object)

pi=3.14

def __init__(self, radius=1):

self.radius= radius

def area(self):

return(self.radius**2)*Circle.pi

def setradius(self, newradius):

self.radius= newradius

def getradius(self):

return self.radius

Inheritance

class Animal(object):

def __init__(self):
print (‘animal created’)

def whoAmI(self):

print (‘Animal’)

def eat(self):

print (‘Eating’)

Class Dog(Animal):

def __init__(self):

Animal.__init__(self)

print (‘Dog created’)

def whoAmI(self):

print( ‘Dog’)

def bark(self):

print (‘Bhoo bhoo’)

d= Dog()

d.eat()

d.bark()

Special Methods

Errors and Exeption Handling


try:

f=open(‘test987’,’r’)

f.write(‘hfiu hjsdk’)

except:

print (‘error in reading’)

else:
print (‘successs’)

def askint():

try:

val= int(raw_input(‘enter integer: ’))

except:

print (‘not integer’)

val= int(raw_input(‘try again: ’))

finally:

print ‘finally executed’

print (val)

def askinteger():

while True:

try:

val= int(raw_input(‘enter integer: ’))

except:

print (‘not integer’)

continue

else:

print (‘correct’)

break

finally:

print (‘finally executed’)

print val

Modules and Packages


import math

math.sqrt(4)

from math import sqrt

sqrt(4)

Pip install pkgname

// github , google search

Built-in Functions
map()

def fahrenheit(T):

return(9.0/5)*T+32

temp[0, 22.5, 36]

map(fahrenheit, temp)

map(lambda T: (9.0/5)*T+32, temp)

reduce()

lst= [1,3,45,878,45,65]

maxfind = lambda a,b: a if (a>b) else b max(lst)

def max_find(a,b):

if a>b:

return a

else:

return b

max_find(12,100)
reduce(max_find, lst)

filter()

evencheck(num): filter out elements for which function returns True

if num%2==0

return True

else:

return False

ls= [1,45,76,2,4,5]

filter(evencheck, ls)

filter(lambda num: num%2==0, lst)

zip()

Aggregates elements from each iterables

a= [1,6,4,85,3,9,0]

b= [2,54,6,9,1,54,23]

zip(a,b)

for pair in zip(a,b):

print(max(pair))

map(lambda pair: max(pair), zip(a,b))

d1= {‘k1’:2, ‘k2’:3}

d1= {‘k3’:4, ‘k4’:6}

zip(d1,d2) returns pair of keys only

zip(d1, d2.itervalues())
def switch(d1, d2)

dout= {}

for d1key, d2val in zip()d1, d2.iteritems()):

dout[d1key]: d2val

return dout

switch(d1,d2)

enumerate()

for i,item in enumerate(lst)

if i>2:

break;

else:

print (item)

l= [True, True, False]

all(l) and any(l)

complex(2,8)

Python Decrorators
s= 'akjhk skjnc kjv'

def fu():

print(locals())

print(globals())

print(globals()['s'])
def fu(name= 'arfe'):

print('hello '+ name)

greet = fu

fu()

greet()

del fu

greet()

% functions within functions

def fu(name= 'arfe'):

print('hello '+ name)

def hello():

print('inside hello fn')

def welcome():

print('inside welcoem fn')

welcome()

hello()

if name= 'arfe':

return hello

else:
return welcome

x= fu()

print(x())

#function as argument

def nd(func):

def wf():

print('code before fn')

func()

print('code after fn')

return wf

def fnd():

print('this fn needs deco')

fnd= nd(fnd)

fnd()

@nd

def fnd():

print('this fn needs deco')

fnd()

python Generators
def gencubes(n):
for num in range(n):

yield num**3

for x in gencubes(10):

print(x)

def gencubes(n):

out=[]

for num in range(n):

out.append(num**3)

return out

for x in gencubes(10):

print(x)

s= 'hello'

for let in s:

print(let)

next(s)

s= 'hello'

s_iter = iter(s)

next(s_iter)

next(s_iter)

next(s_iter)

Advanced Python modules


#Collections module

#counter

from collections import Counter

s='he he ho ka jndj'

lst= [1,1,2,1,1,3,2,4,5,5,3,2,32,4]

Counter(lst)

print(Counter(s))

words=s.split()

print(Counter(words))

c=Counter(words)

print(c.most_common(2))

# check other methods also

#defaultdict

You might also like