0% found this document useful (0 votes)
14 views105 pages

Mod2_ppt

The document provides an overview of lists and dictionaries in Python, detailing their characteristics, methods, and how to manipulate them. It covers topics such as indexing, slicing, list methods, and the differences between mutable and immutable data types. Additionally, it explains the creation and usage of dictionaries, including key-value pairs and methods associated with dictionaries.

Uploaded by

h13584962
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)
14 views105 pages

Mod2_ppt

The document provides an overview of lists and dictionaries in Python, detailing their characteristics, methods, and how to manipulate them. It covers topics such as indexing, slicing, list methods, and the differences between mutable and immutable data types. Additionally, it explains the creation and usage of dictionaries, including key-value pairs and methods associated with dictionaries.

Uploaded by

h13584962
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/ 105

MODULE- 2

LIST
DICTIONARIES AND STRUCTURING DATA
LISTS DATA TYPE
 Lists can contain multiple values in an ordered sequence
 They can also contain other lists
 List values are written within [ ]
 List values are comma-delimited
 List contains different data types
GETTING INDIVIDUAL VALUES IN A LIST WITH
INDEXES
 List indexes are used to access values within a list
 The first index is a zero
GETTING INDIVIDUAL VALUES IN A LIST WITH
INDEXES

 Indexes can be only integer values, not floats.


 Otherwise, a Type Error is caused
GETTING INDIVIDUAL VALUES IN A LIST WITH
INDEXES

 Lists can also contain other list values.


GETTING INDIVIDUAL VALUES IN A LIST WITH
INDEXES

 Lists can have negative indexes


GETTING A LIST FROM ANOTHER LIST
WITH SLICES

 An index can get a single value from a list, a slice


can get several values from a list

 A slice is typed between square brackets

 It has two integers separated by a colon

 The first integer is where the slice starts

 The second integer is where the slice ends(not


included)
GETTING A LIST FROM ANOTHER LIST
WITH SLICES
GETTING A LIST FROM ANOTHER LIST
WITH SLICES

 Slicing can be done


using negative
indexing

 The order in which


the indexes are
specified is important

 Getting a List’s
Length with len()
CHANGING VALUES IN A LIST WITH
INDEXES
CHANGING VALUES IN A LIST WITH
INDEXES
LIST CONCATENATION AND LIST
REPLICATION
LIST CONCATENATION AND LIST
REPLICATION
REMOVING VALUES FROM LISTS WITH DEL
STATEMENTS

 The del statement will delete values at an index in a


list

 All of the values in the list after the deleted value will
be moved up one index
WORKING WITH LISTS
TO CREATE LIST
catNames = [ ]
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == “:
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
USING FOR LOOP WITH LISTS

 The for loops execute a block of code a certain


number of times

 A for loop repeats the code block once for each


item in a list value

 A common Python technique is to use


range(len(someList)) with a for loop to iterate
over the indexes of a list.
EXAMPLE 1.PY
 Write a Python program to sum all the items in a
list.
1.PY
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
ADDING ELEMENTS TO AN EMPTY LIST
USING FOR LOOP WITH LISTS
THE IN AND NOT IN OPERATORS

 in and not in
operators determine
whether a value is
or isn’t in a list

 The expressions
with in and not will
evaluate to a
Boolean value
THE IN AND NOT IN OPERATORS
THE MULTIPLE ASSIGNMENT TRICK
 To assign multiple
variables with the
values in a list in one
line of code

 The number of
variables and the
length of the list must
be exactly equal

 Else it will result in


value error
USING THE ENUMERATE() FUNCTION
WITH LISTS

 Instead of using the range(len(someList))


technique with a for loop to obtain the integer
index of the items in the list

 On each iteration of the loop, enumerate() will


return
 two values:

 the index of the item in the list,


 the item in the list itself
USING THE ENUMERATE() FUNCTION
WITH LISTS

Using range(len(listname)

Using enumerate(listname)
USING THE RANDOM.CHOICE() AND
RANDOM.SHUFFLE() FUNCTIONS WITH LISTS

 The random module has a couple functions that


accept lists for arguments

 The random.choice() function will return a


randomly selected item from the list

 The random.shuffle() function will reorder the


items in a list.

 The random module has to be imported for using


these functions
Using the random.choice() and
random.shuffle() functions with Lists
AUGMENTED ASSIGNMENT OPERATORS
AUGMENTED ASSIGNMENT OPERATORS
METHODS

A method is the same thing as a function, except it


is “called on” a value. For example, if a list value
were stored in spam, you would call the index() list
method on that list like so: spam.index('hello’).

The method part comes after the value, separated


by a period. Each data type has its own set of
methods.
LIST METHODS
 index()

 append()

 insert()

 remove()

 sort()

 reverse()
INDEX() METHOD

 If a value exists in the list, the index of the value


is returned

 If the value isn’t in the list, then Python produces


a ValueError error

 When there are duplicates of the value in the list,


the index of its first appearance is returned
INDEX() METHOD
APPEND() AND INSERT() METHOD
 The append() method call adds the argument to
the end of the list.

 The insert() method can insert a value at any


index in the list.

 The first argument to insert() is the index for


the new value

 The second argument is the new value to be


inserted.
APPEND() AND INSERT() METHOD
APPEND() AND INSERT() METHOD
Methods belong to a single data type. The append() and
insert() methods are list methods and can be called only
on list values, not on other values such as strings or
integers.
REMOVE() METHOD
 The remove() method is passed the value to be removed from
the list
 If the value does not exist in the list, it will result in a
ValueError
 If the value appears multiple times in the list, only the first
instance of the value will be removed
SORT() METHOD
 Lists of number values or lists of strings can be
sorted with the sort() method
 Sorting lists that have both number values and
string values in them cannot be done
 sort() uses “ASCIIbetical order” rather than
actual alphabetical order for sorting strings
SORT() METHOD
• To sort in alphabetical order pass str.lower for the
key keyword argument in the sort() method call

• Pass True for the reverse keyword argument to have


sort() sort the values in reverse order

>>> spam = ['ants', 'cats', 'dogs', 'badgers',


'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants’]
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
EXAMPLE PROGRAM: MAGIC 8 BALL WITH
A LIST

Output:
EXAMPLE PROGRAM: MAGIC 8 BALL WITH
A LIST

Instead of several lines of nearly identical elif statements, you


can create a single list that the code works with.
Output:
SEQUENCE DATA TYPES
 Sequence data types represent ordered sequences
of values

 Python sequence data types include

 Lists

 Strings

 Tuples

 Range objects returned by range()


LIST-LIKE TYPES: STRINGS AND
TUPLES
Lists aren’t the only data types that represent ordered
sequences of values. For example, strings and lists are
actually similar, if you consider a string to be a “list” of
single text characters.
Many of the things you can do with lists can also be done
with strings: indexing; slicing; and using them with for
loops, with len(), and with the in and not in operators.
MUTABLE AND IMMUTABLE DATA TYPES
A list value is a mutable data type: It can have values
added, removed, or changed. However, a string is
immutable: It cannot be changed.

 Mutable data  Immutable data


types types
 int
 List
 float
 Dictionary
 string
 Set
 tuples
STRING IS IMMUTABLE: IT CANNOT BE CHANGED. TRYING
TO REASSIGN A SINGLE CHARACTER IN A STRING RESULTS
IN A TYPEERROR ERROR,

The proper way to “mutate” a string is to use slicing and


concatenation to build a new string by copying from parts of
the old string.
>>> name = 'Zophie a cat’
>>> newName = name[0:7] + 'the' + name[8:12]
>>> name
'Zophie a cat'
>>> newName
'Zophie the cat'
LIST VALUE IS MUTABLE
TUPLE DATA TYPE
 Tuples are typed with parentheses, ( and ), instead of
square brackets, [ and ]

 Tuples are immutable

 Tuples cannot have their values modified, appended,


or removed

 If you have only one value in your tuple, you can


indicate this by placing a trailing comma after the
value inside the parentheses
TUPLE DATA TYPE
CONVERTING TYPES WITH THE LIST() AND TUPLE()
FUNCTIONS
 Converting a tuple to a list is handy if you need a
mutable version of a tuple value.
REFERENCES
 Variables are storing references to the computer
memory locations where the values are stored.

 When a variable is assigned to another variable,


the reference is copied.
Reference
Variable
List
CONTD ….
 spam = [0, 1, 2, 3, 4, 5]  spam = cheese copies
stores a reference to a the reference, not the
list, not the actual list. list.
CONTD ….
 cheese[1] = 'Hello!' modifies the list that
both variables refer to.
PASSING REFERENCES
References are particularly important for
understanding how arguments get passed to functions.
When a function is called, the values of the arguments
are copied to the parameter variables.

Output:
[1, 2, 3, 'Hello']
THE COPY MODULE’S COPY() AND DEEPCOPY() FUNCTIONS

copy.copy(), can be used to make a duplicate copy of


a mutable value like a list or dictionary, not just a
copy of a reference.
THE COPY MODULE’S COPY() AND DEEPCOPY() FUNCTIONS

Figure : cheese = copy.copy(spam) creates a second


list that can be modified independently of the first.
The copy Module’s copy() and deepcopy() Functions

If the list you need to copy contains lists, then


use the copy.deepcopy() function instead of
copy.copy(). The deepcopy() function will
copy these inner lists as well.
CONTD ….
COPYING A LIST USING SHALLOW COPY
ADDING [4, 4, 4] TO OLD_LIST, USING
SHALLOW COPY
ADDING NEW NESTED OBJECT USING
SHALLOW COPY
COPYING A LIST USING SHALLOW COPY
ADDING A NEW NESTED OBJECT IN THE LIST USING
DEEP COPY
IDENTITY AND THE ID( ) FUNCTION

 All data types are objects in Python

 The objects in Python have a unique identity

 The identity of an object is obtained using id()


function

 It returns the memory address where the object is


stored

 The memory address is the free memory on a


computer at a given time
IDENTITY AND THE ID() FUNCTION -
EXAMPLES
DICTIONARIES
 Dictionaries are collection of elements like lists

 Dictionaries have indexes to access the elements

 Dictionary indexes are called keys and its


elements are called values
DICTIONARIES

 In lists the indexes must be integers only

 But, in dictionaries keys can be of any data type


CREATING A DICTIONARY
CREATING A DICTIONARY
 Syntax: dictionary_name = {‘key’ : ’value’}

 Elements of dictionary should be enclosed within


{}

 Every key is mapped to a value


CREATING A DICTIONARY
 The association of a key and a value is called key
– value pair
CREATING A DICTIONARY
 An example of creating a dictionary is as given in
the following slide

 The keys and in a dictionary should be enclosed


within ‘ ‘ if they are non-integers

 The key-value pairs should be separated by a :


(colon) while creating a dictionary
CREATING A DICTIONARY - EXAMPLE

Values

Keys
CREATING AN EMPTY
DICTIONARY
An empty dictionaryUSING DICT
can be created () dict()
using
fucntion
 Elements can be added to an empty dictionary
CREATING AN EMPTY DICTIONARY
USING DICT()
ADDING ELEMENTS TO A DICTIONARY
ADDING ELEMENTS TO A
DICTIONARY
 Elements can be added to an empty dictionary or
to an existing dictionary
 Syntax:

 dictionaryName[Key]
Keys and values should = if
be enclosed in quotes
they are non integers value
ADDING ELEMENTS TO AN EMPTY
DICTIONARY

Note: The order of key – value pair will differ from the order in
which these were created
DICTIONARIES VS. LISTS
 Unlike lists, items in dictionaries are unordered.
The first item in a listbnamed spam would be
spam[0]. But there is no “first” item in a
dictionary.
 While the order of items matters for determining
whether two lists are the same, it does not
matter in what order the key-value pairs are
typed in a dictionary
CONTD ….
CONTD ….
 Dictionaries are not
ordered, they can’t be
sliced like lists.
 Trying to access a key
that does not exist in
a dictionary will result
in a KeyError error
message, much like a
list’s “out-of-range”
IndexError error
message.
CONTD ….
THE KEYS(), VALUES(), AND ITEMS()
METHODS

 keys(), values(), and items() the  spam = {'color': 'red', 'age':


values returned by these methods 42}
are not true lists.  >>> for v in spam.values():
 print(v)
 They cannot be modified and do not  red
have an append() method.
 42
 But these data types (dict_keys,
dict_values, and dict_items, >>> for k in spam.keys():
respectively) can be used in for loops. print(k)

>>> for i in
color
spam.items():
age
print(i)
('color', 'red')
('age', 42)
CONTD . . . .

 >>> spam = {'color': 'red', 'age':


list(spam.keys()) 42}
 >>> for k, v in spam.items():
['color', 'age']  print('Key: ' + k + ' Value: ' +
str(v))
 Key: age Value: 42
 Key: color Value: red
CHECKING WHETHER A KEY OR VALUE EXISTS
IN A DICTIONARY

>>> spam = {'name': 'Zophie', 'age': 7}


 >>> 'name' in spam.keys()
False

True >>> 'color' not in


>>> 'Zophie' in spam.values() spam.keys()
True
True

>>> 'color' in spam


THE GET() METHOD

 It’s tedious to check whether a key exists in a


dictionary before accessing that key’s value.
 Fortunately, dictionaries have a get() method that
takes two arguments: the key of the value to retrieve
and a fallback value to return if that key does not
exist.
WITHOUT USING GET(), THE CODE
WOULD HAVE CAUSED AN ERROR
MESSAGE
ACCESSING DICTIONARIES
ACCESSING DICTIONARIES

Dictionaries are accessed using the keys as indexes


UPDATING VALUES IN A DICTIONARY
MODIFYING VALUES IN A DICTIONARY
The values of any key in a dictionary can be
modified
Before:

After:
THE SETDEFAULT() METHOD

• The first time setdefault() is called, the dictionary in


spam changes to {'color': 'black', 'age': 5, 'name': 'Pooka’}.
• The method returns the value 'black' because this is now
the value set for the key 'color’.
• When spam.setdefault('color', 'white') is called next, the
value for that key is not changed to 'white' because spam
already has a key named 'color’.
• The setdefault() method is a nice shortcut to ensure that
a key exists.
Program to count the number of
occurrences of each letter in a string.

Output:
Pretty
Printing

• If you import the pprint module into your


programs, you’ll have access to the pprint() and
pformat() functions that will “pretty print” a
dictionary’s values.
• This is helpful when you want a cleaner display
of the items in a dictionary than what print()
provides.
Pretty Printing
Output:

The pprint.pprint() function is especially helpful


when the dictionary itself contains nested lists or
dictionaries.
Program to count the number of
occurrences of each letter in a string
without function.

The sample output would be:


Enter a string: Hello World
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd': 1}
USING DATA STRUCTURES TO MODEL
REAL WORLD THINGS
DATA STRUCTURES TO MODEL REAL
WORLD
DATA STRUCTURES TO MODEL REAL
WORLD
DATA STRUCTURES TO MODEL REAL
WORLD
DATA STRUCTURES TO MODEL REAL
WORLD
DATA STRUCTURES TO MODEL REAL
WORLD
NESTED LIST AND DICTIONARIES
NESTED LIST AND DICTIONARIES
NESTED LIST AND DICTIONARIES

You might also like