����Python Programming �
UNIT – II
Chapter-8
Python Programming - Lists, Tuples and Dictionaries
Data structures-Sequence
*
Lists
[10, 20, 30, 40]
['Tamilnadu', 'Karnataka', 'Kerala', ‘Andhra’]
Mar 17, 2022
Lists
*
Lists
*
Creation of List�
# Creating a List
List = [ ]
print("Blank List: ")
print(List)
Output: Blank List: [ ]
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
Output : List of numbers: [10, 20, 14]
*
List
# Creating a List of strings and accessing using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output : List Items Geeks Geeks
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Multi-Dimensional List:
Output : [ ['Geeks', 'For'], ['Geeks'] ]
*
# Creating a List with the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
Output : List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
*
# Creating a List with mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)
Output :
List with the use of Mixed Values:
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
*
Knowing the size of List�
# Creating a List
List1 = [ ]
print(len(List1))
Output : 0
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
Output : 3
*
llist_1 = ['a','b','c','d','e','f']
print(list_1[1:3])
print(list_1[:4])
print(list_1[3:])
Output:
['b', 'c']
['a', 'b', 'c', 'd']
['d', 'e', 'f']
*
Access values in List
*
Updating Value in a List
*
Updating Value in a List
*
Updating Value in a List
*
Nested List
*
Cloning List
*
== and is in list
list1=[1,2,3]
list2=[1,2,3]
#shallow copy
list3=list1
print("list1==list2", list1==list2)
print("list3==list2", list3==list2)
print("list1 is list2", list1 is list2)
print("list3 is list2", list3 is list2)
print("list3 is list1", list3 is list1)
list3.append(4)
print(list1, list3)
# copy
list4=list1.copy()
print("list4 is list1", list4 is list1)
print("list4 == list1", list4 == list1)
list4.append(5)
print(list1, list4)
*
List methods
copy() Returns a copy of the list
count() Returns the number of elements with the specified
value
extend() Add the elements of a list (or any iterable), to the end of
the current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
*
Basic List Operations
*
List operations
*
List Methods
*
List Methods
*
Example
*
Example
*
Using List as Stack
*
Demonstration of Stack Operation
*
Using List as Queue
*
Demonstration of Queue Operation
*
Example
*
Looping in List
*
Looping in List-enumerate() function
*
List- using the range() function
*
List – using iterator (iter() function)
*
����Python Programming �
UNIT – II
Chapter-8
Python Programming - Lists, Tuples and Dictionaries
Data structures-Sequence
*
Lists
[10, 20, 30, 40]
['Tamilnadu', 'Karnataka', 'Kerala', ‘Andhra’]
Mar 17, 2022
Lists
*
Lists
*
Creation of List�
# Creating a List
List = [ ]
print("Blank List: ")
print(List)
Output: Blank List: [ ]
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
Output : List of numbers: [10, 20, 14]
*
List
# Creating a List of strings and accessing using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output : List Items Geeks Geeks
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Multi-Dimensional List:
Output : [ ['Geeks', 'For'], ['Geeks'] ]
*
# Creating a List with the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
Output : List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
*
# Creating a List with mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)
Output :
List with the use of Mixed Values:
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
*
Knowing the size of List�
# Creating a List
List1 = [ ]
print(len(List1))
Output : 0
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
Output : 3
*
llist_1 = ['a','b','c','d','e','f']
print(list_1[1:3])
print(list_1[:4])
print(list_1[3:])
Output:
['b', 'c']
['a', 'b', 'c', 'd']
['d', 'e', 'f']
*
Access values in List
*
Updating Value in a List
*
Updating Value in a List
*
Updating Value in a List
*
Nested List
*
Cloning List
*
== and is in list
list1=[1,2,3]
list2=[1,2,3]
#shallow copy
list3=list1
print("list1==list2", list1==list2)
print("list3==list2", list3==list2)
print("list1 is list2", list1 is list2)
print("list3 is list2", list3 is list2)
print("list3 is list1", list3 is list1)
list3.append(4)
print(list1, list3)
# copy
list4=list1.copy()
print("list4 is list1", list4 is list1)
print("list4 == list1", list4 == list1)
list4.append(5)
print(list1, list4)
*
List methods
copy() Returns a copy of the list
count() Returns the number of elements with the specified
value
extend() Add the elements of a list (or any iterable), to the end of
the current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
*
Basic List Operations
*
List operations
*
List Methods
*
List Methods
*
Example
*
Example
*
Using List as Stack
*
Demonstration of Stack Operation
*
Using List as Queue
*
Demonstration of Queue Operation
*
Example
*
Looping in List
*
Looping in List-enumerate() function
*
List- using the range() function
*
List – using iterator (iter() function
*
TUPLES
tup=(val1, val2, …..valn)
*
*
TUPLES-Example
*
TUPLES-Example
*
Utility of TUPLES
*
Accessing Values in a Tuple
*
Extracting Values from a Tuple
Sorted sorted((9,4,7,1)) (1,4,7,9)
*
Zip zip((1,2),[3,4]) [(1, 3), (2, 4)]
*
Tuple methods
*
Find the index of element in Tuples
*
Counting the Elements in Tuples
*
Tuple Assignment
* Number of values in the right hand side should be same as number of variables in the left hand side
*
Tuples for Returning Multiple values
*
Nested Tuples
*
Dictionary
dictionary_name={ key1:values, key2:value2…., keyn:valuen}
key2:value2
….,
keyn:valuen}
*
Creating a dictionary
Dictionary_name={}
Example 1:
mydict = {}
print("Empty Dictionary: ")
print(mydict)
#This code creates an empty dictionary.
Example 2:
mydict = {1: ‘Mango’, 2: ‘Guava‘, 3:’Strawberry’}
#creates a dictionary with integer keys
print(mydict)
*
Creating a dictionary
Example 3:
mydict = {‘xxx’: 123, ‘yyy’: 456, ‘zzz’ : 789}
print(mydict)
# creates a dictionary with string keys
Example 4:
# creates dictionary with mixed keys
mydict = {‘name’: ‘xxx’, 1: ‘yyy’}
print(mydict)
Example 5:
# creates dictionary with mixed keys and values, that is with string and list
mydict = {‘name’: ‘xxx’, 1:[1,2,3,4]}
print(mydict)
*
Using dict()
# Creating a Dictionary using dict()
mydict = dict({1: 'apple', 2: 'grapes', 3:'mangoes'})
print("\nDictionary using dict(): ")
print(mydict)
# Creating a Dictionary with each item as a Pair
mydict = dict([(1, 'apple'), (2, 'grapes'),(3, 'mangoes')])
print("\nDictionary with each item as a pair: ")
print(mydict)
*
Dictionary comprehension
*
Dictionary comprehension
Dictionary
*
Dictionary
dictionary_name={
key_1:value_1,
key_2:value_2,
key_3:value_3
}
*
Dictionary
dict ( ) function – used to create dictionary
>>> print(dict([('aaa',1),('bbb',6.6),('ccc','rrr')]))
{'aaa': 1, 'bbb': 6.6, 'ccc': 'rrr'}
>>> print(dict((('aaa',1),('bbb',6.6),('ccc','rrr'))))
{'aaa': 1, 'bbb': 6.6, 'ccc': 'rrr'}
>>> x=(dict([('aaa',1),('bbb',6.6),('ccc','rrr')]))
>>> x
{'aaa': 1, 'bbb': 6.6, 'ccc': 'rrr'}
*
Dictionary
*
Accessing Values
*
Adding an item in a dictionary
*
Modifying an item in a dictionary
*
Deleting items in a dictionary
del dictionary_name
*
Deleting items in a dictionary
*
*
>>> dict={1:['aaa']}
>>> print(dict)
{1: ['aaa']}
>>> dict={['aaa']:1}
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
dict={['aaa']:1}
TypeError: unhashable type: 'list'
*
*
Program to check a single key in a dictionary
x={'aaa': 1, 'bbb': 6.6, 'ccc': 'rrr'}
if 'eee' in x:
print('eee exists')
else:
print('eee not exists in dictionary')
Output:
eee not exists in dictionary
*
Sorting items in a dictionary
>>> x={'fff': 1, 'bbb': 6.6, 'zzz': 'rrr'}
>>> print(x.keys())
dict_keys(['fff', 'bbb', 'zzz'])
>>> print(sorted(x.keys()))
['bbb', 'fff', 'zzz']
*
Looping over a dictionary
*
Nested dictionary
*
Built-in Dictionary Functions and Methods
*
Built-in Dictionary Functions and Methods
*
Built-in Dictionary Functions and Methods
*
Built-in Dictionary Functions and Methods
*
Built-in Dictionary Functions and Methods
*
Difference between a list and a dictionary
List | Dictionary |
Ordered set of items | Matches one item (key) with another (value) |
Use number as index to access a particular item | Use any type (immutable) of value as an index to access a particular item |
Used to look up a value | Used to take one value and look up another value |
| No need to search for a value one by one in the entire set of values, can find a value instantly |
| Key-value pair may not be displayed in the order in which it was specified – uses complex algorithms called hashing to provide fast access to the items stored in the dictionary |
*
String formatting with dictionary
%s, %d, %f etc., can be used to represent string, integer, floating point number, or any other data
x={'fff': 1, 'bbb': 2, 'zzz': 3}
for key, val in x.items():
print("%s key : value %d" %(key,val))
Output:
fff key : value 1
bbb key : value 2
zzz key : value 3
*
�when to use which data structure?�
*
�List vs Tuple vs Dictionary�
*
�List vs Tuple vs Dictionary�
*
mcm={x:x*100 for x in range(1,11)}
temp=mcm.values()
print(temp)
cmm={x:x/100 for x in temp}
print("meter:centimeter",mcm)
print("centimeter:meter",cmm)
Output:
dict_values([100, 200, 300, 400, 500, 600, 700, 800, 900, 1000])
meter:centimeter {1: 100, 2: 200, 3: 300, 4: 400, 5: 500, 6: 600, 7: 700, 8: 800, 9: 900, 10: 1000}
centimeter:meter {100: 1.0, 200: 2.0, 300: 3.0, 400: 4.0, 500: 5.0, 600: 6.0, 700: 7.0, 800: 8.0, 900: 9.0, 1000: 10.0}
>>>
*
*
*
*
*
dict={0:0,1:1}
def fib(n):
if n not in dict:
val=fib(n-1)+ fib(n-2)
dict[n]=val
return dict[n]
n=int(input("enter the value of n"))
print("fib=",fib(n))
print("dict=",dict);
enter the value of n5
fib= 5
dict= {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
*
*
*
*
*
*
*
*
*
Thank you