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

Python Collections

Uploaded by

debghosh1980
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)
9 views

Python Collections

Uploaded by

debghosh1980
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/ 34

PYTHON-COLLECTIONS Chandreyee Chowdhury

SUMMARY OF LIST METHODS

❑•L.append() : Adds one item to the end of the list.


❑•L.extend(<list>) : Adds multiple items to the end of the list.
❑•L.pop(i) : Remove item ‘i’ from the list. Default:Last.
❑•L.reverse() : Reverse the order of items in list.
❑•L.insert(i,item): Inserts ‘item’ at position i.
❑•L.remove(item) : Finds ‘item’ in list and deletes it from the list.
❑•L.sort(): Sorts the list in-place i.e., changes the sequence in the list.
IF STATEMENT
❑If statements can check single condition

❑Multiple conditions could be combined through and/or


if car!=‘bmw’ or car!=‘Toyota’:
print(car.title())
LIST WITH IF
❑You can do some interesting work when you combine lists and if statements.
❑You can watch for special values that need to be treated differently than other values in the
list.
❑You can manage changing conditions efficiently, such as the availability of certain items in a
restaurant
car='maruti'
if car in cars:
print(car.upper())
SEARCHING FOR AN ITEM else:
print(car.title() + " is not
present in the list")

If a value appears or does not appear in the list

if-else
if-elif-else
Make a list of five or more usernames, including the name 'admin’.
Imagine you are writing code that will print a greeting to each user after they
log in to a website. Loop through the list, and print a greeting to each user:
LIST WITH IF • If the username is 'admin', print a special greeting, such as Hello admin,
would you like to see a status report?
• Otherwise, print a generic greeting, such as Hello Eric, thank you for logging
in again.
Add an if test to hello_admin.py to make sure the list of users is not empty.

userList=['admin', 'user1', 'user2', 'user3’]


if userList:
for user in userList:
if user.lower()=='admin':
print("Hello Admin!")
else:
print("Welcome back " + user)
FINDING LIST INTERSECTION
if newUserList:
for user in newUserList:
if user in userList:
print(user + " is already in use")
else:
print(user + " is available")
MULTI DIMENSIONAL LIST
My2DList=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

Two dimensions

my2DList = [[1,2,3,’a’],[5,6,7],[9,10,’e’,12,’cat’],[’beta’,14,15,16]]

https://www.purdue.edu/hla/sites/varalalab/wp-content/uploads/sites/20/2018/03/Lecture_10.pdf
EXAMPLES
mat = ((1, 2, 3, 5), (4.5, "a",
"b", "c"))
for j in mat:
for k in j:
print(k,end = " ")
print()

Slide from Carnegie Mellon University in Qatar


DICTIONARIES
❑Dictionaries are unordered collections of objects, optimized for quick searching.
❑ Instead of an index, objects are identified by their ‘key’.
❑ Each item within a dictionary is a ‘key’:’value’ pair.

❑ A key’s value can be a number, a string, a list, or even another dictionary


❑Like lists and tuples, they can be variable-length, heterogeneous and of arbitrary depth.
❑’Keys’ are mapped to memory locations by a hash function
HolidayDictionary.py
ADDING TO A DICTIONARY
person={}
name=input("enter your name: ")
email_id=input("enter your email_id")
phone_no=input("enter your ph_no")
person[name]=[phone_no,email_id]
person={}
flag=True
while flag:
name=input("enter your name: ")
Syntax of while if name=="quit":
flag=False
break
email_id=input("enter your email_id: ")
phone_no=input("enter your ph_no: ")

person[name]=[phone_no,email_id]
COMMON METHODS OF DICTIONARY

❑ D.keys() : List of keys


❑ D.values() : List of values
❑ D.clear() : remove all items
❑ Modifying a value in a Dictionary: D[<key>]=<new value>
❑ removing a key-value pair: del D[<key>]
❑ D.update(D2) : Merge key values from D2 into D.
❑ Overwrites any matching keys in D.
❑D.pop(key) : returns the value of given key and removes this key:value pair from dictionary.
TRAVERSING THROUGH A DICTIONARY

for key, value in D.items():


print("\nKey: " + key)
print("Value: " + value)

Looping through all the keys in a dictionary


for v in D.keys():
print(v.title())
Looping through all the values in a dictionary
for v in sorted(D.values()):
print(v.title())
NESTING IN DICTIONARY

❑A list can be nested in a dictionary


❑A dictionary could be nested in a dictionary
❑You should not nest lists and dictionaries too deeply
❑That indicates bad coding practice
NESTED DICTIONARY

Traversing through a nested dictionary using while loop


def identity(message):
return message

FUNCTIONS print(identity(“Hello Everyone”))

❑A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provides better modularity for your application and a high degree of code
reusing.
❑As you already know, Python gives you many built-in functions like print() etc. but you can
also create your own functions. These functions are called user-defined functions.
❑Any indented lines that follow def identity(): make up the body of the function.
❑A function call tells Python to execute the code in the function
FUNCTIONS
❑The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
❑The code block within every function starts with a colon (:) and is indented.
❑The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
❑Syntax:
❑def function_name( parameters ):
‘’’function_docstring’’’
function_suite By default, parameters have a positional behavior, and
you need to inform them in the same order that they were
return [expression] defined
RESOLVING PARAMETER TYPES

❑We don’t declare the types of the parameters, relying instead on duck typing; that is, as long
as the parameter argument has the attributes our function expects to operate upon, we don’t
care about its real type
❑Wikipedia has a nice, concise explanation of duck typing: “A style of typing in which an
object’s methods and properties determine the valid semantics, rather than its inheritance
from a particular class or implementation of an explicit interface.”
❑The name of the concept refers to the duck test, attributed to James Whitcomb Riley, which
is phrased as follows: “When I see a bird that walks like a duck, and swims like a duck, and
quacks like a duck, I call that bird a duck.”
❑ In a duck-typed language, the function would take an object of any type, and
simply call its walk and quack methods, producing a runtime error if they are not
defined
PASS BY REFERENCE VS VALUE
❑All parameters (arguments) in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function.
def changeme( mylist ):
'''This changes a passed list’‘’
myList.append(56)
print("Values inside the function: " + str(mylist))
return

mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: “ + str(mylist))
❑There is one more example where argument is being passed by reference but inside the function, but
the reference is being over-written.
def changeme( mylist ):
'''This changes a passed list'''
mylist = [1,2,3,4]
print("Values inside the function: " + str(mylist))
return

mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

❑The parameter mylist is local to the function changeme. Changing mylist within the function does not
affect mylist. The function accomplishes nothing and finally this would produce following result:

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]
Traceback (most recent call last):
File "test.py", line 11, in
ARGUMENTS <module> printme();
TypeError: printme() takes exactly
1 argument (0 given)

❑ Function Arguments:
A function by using the following types of formal arguments::
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
❑ Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
printme();
ORDER MATTERS IN POSITIONAL ARGUMENTS

def build_person(fname, lname, age):


person={'fname':fname, 'lname':lname, ‘age’:age}
print(“Hello “ + fname + “ “ + lname)
return person

build_person(‘Alan’, ‘Turing’, 42)


build_person(42, ‘Alan’, ‘Turing’)

❑If a list is passed as an argument and we don’t want to change its values through the
function, then pass a copy of the list instead
function_name(list_name[:])
def build_person(fname, lname, age):
person={'fname':fname,
'lname':lname, ‘age’:age}
KEYWORD ARGUMENTS print(“Hello “ + fname + “ “ +
lname)
return person

❑Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
❑This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters.
❑ p=build_person(fname=‘Alan’,lname=‘Turing’, age=42)
❑ p=build_person(age=42, fname=‘Alan’,lname=‘Turing’)
DEFAULT ARGUMENTS

❑ A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
❑ Following example gives idea on default arguments, it would print default age if it is not
passed:
def printinfo( name, age = 35 ):
print("Name: “ + name)
print("Age “ + age)
return

printinfo( age=50, name="miki" )


printinfo( name="miki" )
This would produce following result:
Name: mili Age 50 Name: mili Age 35
VARIABLE-LENGTH ARGUMENTS

❑You may need to process a function for more arguments than you specified while defining the
function.
❑These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
❑The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
VARIABLE LENGTH ARGUMENTS

make_pizza(16)

❑If you want a function to accept several different kinds of arguments, the parameter
that accepts an arbitrary number of arguments must be placed last in the function
definition.
❑Python matches positional and keyword arguments first and then collects any
remaining arguments in the final parameter.
def build_person(fname, lname, age='',
**otherDetails):
person={'fname':fname,
VARIABLE KEYWORD ARGUMENT 'lname':lname}
if age:
person['age']=age
if otherDetails:
for key, value in
otherDetails.items():
person[key]=value
return person

❑Sometimes you’ll want to accept an arbitrary number of arguments, but you won’t know
ahead of time what kind of information will be passed to the function.
❑ In this case, you can write functions that accept as many key-value pairs as the calling
statement provides
RETURN VALUES

❑ The return statement takes a value from inside a function and sends it back to the line that called the
function
❑ A function can return any kind of value you need it to, including more complicated data structures
like lists and dictionaries
❑ A function may return multiple values
❑ When a function returns multiple comma-separated values, Python automatically wraps them up into
a tuple data structure and returns that tuple to the caller.
❑ This is a feature called automatic tuple packing.
❑ You may make this packing more explicit by wrapping up your return values in a tuple yourself but
this is neither required, nor encouraged
UNPACKING A TUPLE
a, b, c = multi_return()

The leading single asterisk is Python notation to unpack


the tuple values while the leading double asterisk unpacks
the dict values.
lambda y,z:y+z

ANONYMOUS FUNCTIONS

❑“Functions as first-class objects” is a powerful idea to digest and necessitates a change in


how we structure our programs.
❑Everything should not be modelled as a class . After all, not everything is a noun and some
things are best described using verbs!
❑Behviour parameterization
❑ You can use the lambda keyword to create small anonymous functions. These functions are
called anonymous because they are not declared in the standard manner by using the def
keyword.
❑ Functions in Python can be passed around and assigned to variables, just like any other
object.

result = filter(lambda x: x % 2 != 0, seq)


In this case, when someone calls make_function, it returns another function whose definition
depends on the parameter passed to make_function.

1. Here, we begin defining a


function named make_function,
starting with the docstring.
2. Next, we use the lambda
keyword to define a one line,
anonymous function that we
assign to matches_parity.
The lambda function assigned to
matches_parity depends on the
value of the parity function
argument.
3. If the parameter argument value
is neither odd nor even, we raise
the built-in AttributeError
exception.
❑4. We now define a get_by_parity
function within the enclosing
function’s body.
❑You’ll notice that the value of
matches_parity is used here.
❑It is similar to capturing final
fields from enclosing scopes inside
anonymous class declarations in
Java.
❑5. Finally, we return the
get_by_parity function object from
make_function.
MODULE
❑Functions could be stored in a separate file called a module
❑An import statement tells Python to make the code in a module available in the currently
running program file
❑It also allows you to reuse functions in many different programs
IMPORTING A MODULE

import pizza
pizza.make_pizza(16, ‘extra cheese’)
❑ from module_name import *

❑This approach to importing, in which you simply write import followed by the name of the module,
makes every function from the module available in your program
❑Importing specific functions-from module_name import function_name
❑ from module_name import function_0, function_1, function_2
❑Putting an alias for the module name
❑from module_name import function_name as fn

You might also like