1 of 128

����Python Programming �

​

​

​

​

​

​

UNIT – II

​

Chapter-8

Python Programming - Lists, Tuples and Dictionaries

​

​

2 of 128

Data structures-Sequence

  • Data structure:
    • A Data structure is a group of elements that are put together under one name.
    • It defines a particular way of storing and organizing data in a computer so that it can be used efficiently
  • Sequence:
    • It is most basic data structure in Python
    • In sequence, each element has a specific index
    • Index starts with 0 and it is automatically incremented for the next element
    • Example: string(It is a sequence of characters), List, Tuple, Dictionary
    • Python has built-in functions to manipulate the elements
    • Operations: slicing, indexing, adding, multiplying and checking for membership

*

3 of 128

Lists

  • It is sequence data structure. Like a string, List is a sequence of values. In a string, the values are characters;
  • In a list, they can be any type. The values in list are called elements or sometimes items.
  • There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40]

['Tamilnadu', 'Karnataka', 'Kerala', ‘Andhra’]

  • The first example is a list of four integers.
  • The second is a list of three strings.

​

Mar 17, 2022

4 of 128

Lists

  • It is sequence data structure
  • Elements are written as a list of comma separated values between square brackets ([ ])
  • Elements may be different data types
  • List is mutable – means elements can be changed

​

​

​

  • Example

​

*

5 of 128

Lists

  • Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java)
  • A single list may contain DataTypes like Integers, Strings, as well as Objects.
  • Lists are mutable, and hence, they can be altered even after their creation. List us mutable – Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list.
  • List in Python are ordered and have a definite count.
  • The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index.
  • Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.

​

*

6 of 128

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]

​

*

7 of 128

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'] ]

*

8 of 128

# 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]

​

*

9 of 128

# 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']

*

10 of 128

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

​

*

11 of 128

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']

​

*

12 of 128

Access values in List

  • Lists can be sliced and concatenated
  • Syntax of Slice operation:

​

*

13 of 128

Updating Value in a List

  • Append new values in the list with append()

​

*

14 of 128

Updating Value in a List

  • Remove existing value from the list with del

​

*

15 of 128

Updating Value in a List

*

16 of 128

Nested List

  • List within another list

*

17 of 128

Cloning List

*

18 of 128

== 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)

*

19 of 128

List methods

  • Method Description append()Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list

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

*

20 of 128

Basic List Operations

*

21 of 128

List operations

*

22 of 128

List Methods

*

23 of 128

List Methods

*

24 of 128

Example

*

25 of 128

Example

*

26 of 128

Using List as Stack

  • It is a Last-In-First-Out data structure

​

​

​

​

​

​

  • Use of Stack: Function call

​

​

*

27 of 128

Demonstration of Stack Operation

*

28 of 128

Using List as Queue

  • It is the First-in-First-Out data structure (FIFO)
  • Real time Scenario

​

​

​

​

​

​

  • Applications of Queue in Computer Systems:

*

29 of 128

Demonstration of Queue Operation

*

30 of 128

Example

*

31 of 128

Looping in List

  • List elements can be accessed by using,

​

​

​

  • Example

​

​

*

32 of 128

Looping in List-enumerate() function

  • Used to get index as well as item from the list

*

33 of 128

List- using the range() function

  • used to print index of the items

*

34 of 128

List – using iterator (iter() function)

  • An iterator is an object that contains a countable number of values.
  • Used to loop over the elements of the list.
  • Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

*

35 of 128

����Python Programming �

​

​

​

​

​

​

UNIT – II

​

Chapter-8

Python Programming - Lists, Tuples and Dictionaries

​

​

36 of 128

Data structures-Sequence

  • Data structure:
    • A Data structure is a group of elements that are put together under one name.
    • It defines a particular way of storing and organizing data in a computer so that it can be used efficiently
  • Sequence:
    • It is most basic data structure in Python
    • In sequence, each element has a specific index
    • Index starts with 0 and it is automatically incremented for the next element
    • Example: string(It is a sequence of characters), List, Tuple, Dictionary
    • Python has built-in functions to manipulate the elements
    • Operations: slicing, indexing, adding, multiplying and checking for membership

*

37 of 128

Lists

  • It is sequence data structure. Like a string, List is a sequence of values. In a string, the values are characters;
  • In a list, they can be any type. The values in list are called elements or sometimes items.
  • There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40]

['Tamilnadu', 'Karnataka', 'Kerala', ‘Andhra’]

  • The first example is a list of four integers.
  • The second is a list of three strings.

​

Mar 17, 2022

38 of 128

Lists

  • It is sequence data structure
  • Elements are written as a list of comma separated values between square brackets ([ ])
  • Elements may be different data types
  • List is mutable – means elements can be changed

​

​

​

  • Example

​

*

39 of 128

Lists

  • Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java)
  • A single list may contain DataTypes like Integers, Strings, as well as Objects.
  • Lists are mutable, and hence, they can be altered even after their creation. List us mutable – Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list.
  • List in Python are ordered and have a definite count.
  • The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index.
  • Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.

​

*

40 of 128

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]

​

*

41 of 128

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'] ]

*

42 of 128

# 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]

​

*

43 of 128

# 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']

*

44 of 128

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

​

*

45 of 128

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']

​

*

46 of 128

Access values in List

  • Lists can be sliced and concatenated
  • Syntax of Slice operation:

​

*

47 of 128

Updating Value in a List

  • Append new values in the list with append()

​

*

48 of 128

Updating Value in a List

  • Remove existing value from the list with del

​

*

49 of 128

Updating Value in a List

*

50 of 128

Nested List

  • List within another list

*

51 of 128

Cloning List

*

52 of 128

== 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)

*

53 of 128

List methods

  • Method Description append()Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list

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

*

54 of 128

Basic List Operations

*

55 of 128

List operations

*

56 of 128

List Methods

*

57 of 128

List Methods

*

58 of 128

Example

*

59 of 128

Example

*

60 of 128

Using List as Stack

  • It is a Last-In-First-Out data structure

​

​

​

​

​

​

  • Use of Stack: Function call

​

​

*

61 of 128

Demonstration of Stack Operation

*

62 of 128

Using List as Queue

  • It is the First-in-First-Out data structure (FIFO)
  • Real time Scenario

​

​

​

​

​

​

  • Applications of Queue in Computer Systems:

*

63 of 128

Demonstration of Queue Operation

*

64 of 128

Example

*

65 of 128

Looping in List

  • List elements can be accessed by using,

​

​

​

  • Example

​

​

*

66 of 128

Looping in List-enumerate() function

  • Used to get index as well as item from the list

*

67 of 128

List- using the range() function

  • used to print index of the items

*

68 of 128

List – using iterator (iter() function

  • An iterator is an object that contains a countable number of values.
  • Used to loop over the elements of the list.
  • Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

*

69 of 128

TUPLES

  • Sequence of immutable objects separated by comma.
  • Defined within parenthesis ()
  • Creating a tuple:

tup=(val1, val2, …..valn)

    • Val1, val2 …. valn may be same or different datatypes
    • Any set of multiple comma-separated values without [ ] or { } or ( ) are treated as tuples by default.

*

70 of 128

*

TUPLES-Example

71 of 128

*

TUPLES-Example

72 of 128

*

Utility of TUPLES

  • Tuples are useful for representing records/structures as in other programming languages.
  • Some built-in functions return tuples.

​

73 of 128

*

Accessing Values in a Tuple

  • Using index each element can be accessed.
  • Index starts with 0.
  • Operations – slice, concatenate

​

74 of 128

*

Extracting Values from a Tuple

  • Updation and deletion is not possible in Tuple since it is immutable
  • Extracting the values from one tuple to another tuple is possible

75 of 128

Sorted sorted((9,4,7,1)) (1,4,7,9)

*

Zip zip((1,2),[3,4]) [(1, 3), (2, 4)]

76 of 128

*

Tuple methods

  • Only two methods
  • count() and index()

77 of 128

*

Find the index of element in Tuples

  • To find the index of an element in the tuple, index() method is used.
  • Syntax: tup.index(obj)
  • If the object is not present, error is generated.

​

78 of 128

*

Counting the Elements in Tuples

  • To find the number of specific elements
  • Syntax: tup.count(obj)

​

79 of 128

*

Tuple Assignment

* Number of values in the right hand side should be same as number of variables in the left hand side

80 of 128

*

Tuples for Returning Multiple values

  • If we need to return more than one values from function we can use tuples.

​

81 of 128

*

Nested Tuples

  • We can define a tuple in another tuple called nested tuple.
  • We can also specify list within tuple.

82 of 128

*

Dictionary

  • Dictionary is a data structure in which we store values as a pair of key and value.
  • Each key is separated by a colon (:) and consecutive items are separated by commas.
  • All the items are enclosed in {}
  • The syntax is :

dictionary_name={ key1:values, key2:value2…., keyn:valuen}

  • We can also write as
  • dictionary_name={ key1:values,

key2:value2

….,

keyn:valuen}

  • Keys in a dictionary must be unique and be of any immutable objects (like int, string, tuple )
  • Dictionaries are not sequences, but they are mappings. Mappings are collections of objects that store objects by key instead of by position (index)

​

83 of 128

*

Creating a dictionary

  • Creating an empty dictionary

Dictionary_name={}

​

Example 1:

mydict = {}

print("Empty Dictionary: ")

print(mydict)

#This code creates an empty dictionary.

​

  • To create a dictionary with items

Example 2:

mydict = {1: ‘Mango’, 2: ‘Guava‘, 3:’Strawberry’}

#creates a dictionary with integer keys

print(mydict)

​

​

84 of 128

*

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)

85 of 128

*

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)

86 of 128

*

Dictionary comprehension

  • Another way of creating a dictionary

​

​

  • Example

​

​

87 of 128

*

Dictionary comprehension

  • Another way of creating a dictionary

​

​

  • Example

​

​

88 of 128

Dictionary

*

89 of 128

Dictionary

  • Data structure
  • Store values as a pair of key and value
  • Each key is separated from its value by a colon(:)
  • Consecutive items are separated by comma
  • Entire item in dictionary is enclosed in curly brackets ({})
  • Syntax

dictionary_name={

key_1:value_1,

key_2:value_2,

key_3:value_3

}

  • keys in the dictionary must be of unique and be of any immutable data type (strings, numbers, or tuples)
  • values need not be unique and can be of any data type
  • keys are case-sensitive

​

*

90 of 128

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'}

*

91 of 128

Dictionary

  • Dictionary comprehension–create dictionary based on existing dictionary
  • Syntax

​

​

  • expression generates elements of dictionary from items in the sequence that satisfy the condition

​

​

​

​

​

​

​

​

*

92 of 128

Accessing Values

  • square brackets are used along with the key to obtain its value

​

​

​

​

​

​

​

  • a KeyError is generated, if we try to access an item with a key, which is not specified in the dictionary

​

​

​

​

​

​

​

​

*

93 of 128

Adding an item in a dictionary

  • syntax

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

*

94 of 128

Modifying an item in a dictionary

  • just overwrite the existing value

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

*

95 of 128

Deleting items in a dictionary

  • del – one or more items
  • clear()- delete or remove all the items
  • To remove an entire dictionary form the memory

del dictionary_name

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

*

96 of 128

Deleting items in a dictionary

  • pop() method – removes an item from the dictionary and returns its value
  • if specified key is not present, default value is returned
  • if specified key is not present, and if the default value is not specified, then it returns the KeyError

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

*

97 of 128

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

*

98 of 128

  • value can be of any type, mutable or immutable

>>> dict={1:['aaa']}

>>> print(dict)

{1: ['aaa']}

​

  • key can be only immutable, it cannot be mutable,
  • so, key cannot be a List, since list is mutable

​

>>> dict={['aaa']:1}

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

dict={['aaa']:1}

TypeError: unhashable type: 'list'

*

99 of 128

  • if key contains any mutable object directly or indirectly in a tuple, then TypeError is generated

*

100 of 128

Program to check a single key in a dictionary

  • in keyword is used

​

​

​

​

​

​

​

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

*

101 of 128

Sorting items in a dictionary

  • keys() method-returns a list of all the keys in the dictionary in an arbitrary order

>>> x={'fff': 1, 'bbb': 6.6, 'zzz': 'rrr'}

>>> print(x.keys())

​

dict_keys(['fff', 'bbb', 'zzz'])

​

  • sorted() function used to sort the keys

​

>>> print(sorted(x.keys()))

['bbb', 'fff', 'zzz']

​

​

​

​

​

*

102 of 128

Looping over a dictionary

​

​

​

​

*

103 of 128

Nested dictionary

​

​

​

​

*

104 of 128

Built-in Dictionary Functions and Methods

*

105 of 128

Built-in Dictionary Functions and Methods

*

106 of 128

Built-in Dictionary Functions and Methods

*

107 of 128

Built-in Dictionary Functions and Methods

*

108 of 128

Built-in Dictionary Functions and Methods

*

109 of 128

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

*

110 of 128

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

*

111 of 128

�when to use which data structure?�

​

  • Use lists to store a collection of data that does not need random access
  • Use lists if the data has to be modified frequently
  • Use tuples when data should not be altered

​

*

112 of 128

�List vs Tuple vs Dictionary�

  • Can append a new item in a list, since list is mutable
  • Cannot append new item in tuple, since tuple is immutable
  • Tuple has fixed size, cannot add or delete items from it

​

​

​

*

113 of 128

�List vs Tuple vs Dictionary�

  • tuples are easier on memory and processor, and achieves performance optimization
  • tuples are best used as heterogeneous collections
  • lists are best used as homogeneous collections
  • Dictionary are best data structure for frequent lookup operations

​

​

​

*

114 of 128

​

​

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}

>>>

​

*

115 of 128

*

116 of 128

*

117 of 128

*

118 of 128

*

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}

119 of 128

*

120 of 128

*

121 of 128

*

122 of 128

*

123 of 128

*

124 of 128

*

125 of 128

*

126 of 128

*

127 of 128

*

128 of 128

Thank you