Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lists, Tuples, and Dictionaries in Python, Study notes of Computer Applications

An overview of compound data types in Python, including lists, tuples, and dictionaries. It covers list operations, list slices, list methods, list loops, mutability, aliasing, and cloning lists. The document also includes examples of advanced list processing, such as list comprehension, and illustrative programs like selection sort, insertion sort, merge sort, and quick sort. Additionally, it explains the syntax and usage of for loops, while loops, and infinite loops in Python. Finally, it discusses the concept of mutability and aliasing in lists.

Typology: Study notes

2022/2023

Available from 02/10/2024

karthik-a-nair
karthik-a-nair 🇮🇳

5 documents

1 / 23

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIT IV
COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples, tuple assignment, tuple as return value; Dictionaries:
operations and methods; advanced list processing - list comprehension, Illustrative
programs: selection sort, insertion sort, merge sort, quick sort.
Lists
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets[ ].
Items in the lists can be of different data types.
Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
operations
examples
description
create a list
>>> a=[2,3,4,5,6,7,8,9,10]
in this way we can create a
>>> print(a)
list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0])
Accessing the item in the
Indexing
2
position 0
>>> print(a[8])
Accessing the item in the
10
position 8
>>> print(a[-1])
Accessing a
last element
10
using negative indexing.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Lists, Tuples, and Dictionaries in Python and more Study notes Computer Applications in PDF only on Docsity!

UNIT IV

COMPOUND DATA: LISTS, TUPLES, DICTIONARIES

Lists , list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,

list parameters; Tuples , tuple assignment, tuple as return value; Dictionaries :

operations and methods; advanced list processing - list comprehension, Illustrative

programs: selection sort, insertion sort, merge sort, quick sort.

Lists

 List is an ordered sequence of items. Values in the list are called elements / items.

It can be written as a list of comma-separated items (values) between square

brackets[ ].

Items in the lists can be of different data types.

Eg: a= [10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]

The following list contains a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]]

A list within another list is nested. A list that contains no elements is called an empty

list; you can create one with empty brackets, [].

As you might expect, you can assign list values to variables:

cheeses = ['Cheddar', 'Edam', 'Gouda']

numbers = [17, 123]

empty = []

print cheeses, numbers, empty

['Cheddar', 'Edam', 'Gouda'] [17, 123] []

Operations on list:

  1. Indexing
  2. Slicing
  3. Concatenation
  4. Repetitions
  5. Updating
  6. Membership
  7. Comparison

operations examples description

create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a

print(a) list at compile time

[2, 3, 4, 5, 6, 7, 8, 9, 10]

print(a[0]) Accessing the item in the

Indexing 2 position 0

print(a[8]) Accessing the item in the

10 position 8

print(a[-1]) Accessing a last element

10 using negative indexing.

print(a[0:3])

Slicing [2, 3, 4]

print(a[0:]) Printing a part of the list.

[2, 3, 4, 5, 6, 7, 8, 9, 10]

b=[20,30] Adding and printing the

Concatenation >>> print(a+b) items of two lists.

[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]

print(b*3) Create a multiple copies of

Repetition [20, 30, 20, 30, 20, 30] the same list.

print(a[2])

4 Updating the list using

Updating >>> a[2]=100 index value.

print(a)

[2, 3, 100, 5, 6, 7, 8, 9, 10]

a=[2,3,4,5,6,7,8,9,10]

5 in a

Membership True Returns True if element is

100 in a present in list. Otherwise

False returns false.

2 not in a

False

a=[2,3,4,5,6,7,8,9,10]

Comparison

b=[2,3,4] Returns True if all elements

a==b in both elements are same.

False Otherwise returns false

a!=b

True

List slices:

List slicing is an operation that extracts a subset of elements from an list and packages

them as another list.

Syntax:

Listname[start:stop]

Listname[start:stop:steps]

default start value is 0

 default stop value is n-

 

 [:] this will print the entire list

 

 [2:2] this will create a empty slice

a.index(element)

a=[0, 1, 2, 3, 8,5, 6, 7, 8,9]

a.index(8)

Returns the index of

the first matched

item

sum()

a=[1,2,3,4,5]

sum(a)

print(a)

[0, 1, 2, 3, 4, 5, 6, 7, 8,9]

Sort items in a list in

ascending order

a.reverse()

a.reverse()

print(a)

[8, 7, 6, 5, 4, 3, 2, 1, 0]

Reverse the order of

items in the list

7 a.pop()

a=[8, 7, 6, 5, 4, 3, 2, 1, 0]

a.pop() Removes and

print(a)

=[8, 7, 6, 5, 4, 3, 2, 1] returns an element

at the last element

8 a.pop(index) >>> a.pop(0) Remove the

print(a)

[7, 6, 5, 4, 3, 2, 1, 0] particular element

and return it.

9 a.remove(element)

a=[7, 6, 5, 4, 3, 2, 1]

a.remove(1) Removes an item

print(a) from the list

[7, 6, 5, 4, 3, 2]

10 a.count(element)

a=[7, 6, 5, 4, 3, 2,6]

a.count(6) Returns the count of

2 number of items

passed as an

argument

11 a.copy()

a=[7, 6, 5, 4, 3, 2]

b=a.copy() Returns a

print(b) copy of the list

[7, 6, 5, 4, 3, 2]

12 len(list)

a=[7, 6, 5, 4, 3, 2]

len(a) return the length of

6 the length

17 sum(list)

a=[7, 6, 5, 4, 3, 2]

sum(a) return the sum of

27 element in a list

14 max(list) >>> max(a) return the maximum

element in a list.

15 a.clear() >>> a.clear() Removes all items

print(a) from the list.

[ ]

16 del(a) >>> del(a) delete the entire list.

print(a)

Error: name 'a' is not

defined

List loops:

**1. For loop

  1. While loop
  2. Infinite loop**

List using For Loop:

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other

iterable objects.

Iterating over a sequence is called traversal.

 Loop continues until we reach the last item in the sequence.

 

 The body of for loop is separated from the rest of the code using indentation.

Syntax:

for val in sequence:

Accessing element output

a=[10,20,30,40,50] 10

for i in a: 20

print(i) 30

Accessing index output

a=[10,20,30,40,50] 0

for i in range(0,len(a),1): 1

print(i) 2

Accessing element using range: output

a=[10,20,30,40,50] 10

for i in range(0,len(a),1): 20

print(a[i]) 30

Example description

a=[1,2,3,4,5]

a[0]=

print(a)

[100, 2, 3, 4, 5]

changing single element

a=[1,2,3,4,5]

a[0:3]=[100,100,100]

print(a)

[100, 100, 100, 4, 5]

changing multiple element

a=[1,2,3,4,5] The elements from a list can also be

a[0:3]=[ ] removed by assigning the empty list to

print(a) them.

[4, 5]

a=[1,2,3,4,5] The elements can be inserted into a list by

a[0:0]=[20,30,45] squeezing them into an empty slice at the

print(a) desired location.

[20,30,45,1, 2, 3, 4, 5]

Aliasing(copying):

 Creating a copy of a list is called aliasing.

 When you create a copy both the list will be having same memory location.

 

 changes in one list will affect another list.

 

Alaising refers to having different names for same list values.

Example Output:

a= [1, 2, 3 ,4 ,5]

b=a

print (b) [1, 2, 3, 4, 5]

a is b True

a[0]=

print(a) [100,2,3,4,5]

print(b) [100,2,3,4,5]

In this a single list object is created and modified using the subscript operator.

When the first element of the list named “a” is replaced, the first element of the list

named “ b” is also replaced.

This type of change is what is known as a side effect. This happens because after

the assignment b=a , the variables a and b refer to the exact same list object.

They are aliases for the same object. This phenomenon is known as aliasing.

To prevent aliasing, a new object can be created and the contents of the original

can be copied which is called cloning.

Clonning:

 To avoid the disadvantages of copying we are using cloning.

 Creating a copy of a same list of elements with two different memory locations is called cloning.

 Changes in one list will not affect locations of aother list.

Cloning is a process of making a copy of the list without modifying the original list.

  1. Slicing
  2. list()method
  3. copy() method

clonning using Slicing

a=[1,2,3,4,5]

b=a[:]

print(b)

[1,2,3,4,5]

a is b

False #because they have different memory location

clonning using List( ) method

a=[1,2,3,4,5]

b=list

print(b)

[1,2,3,4,5]

a is b

false

a[0]=

print(a)

a=[100,2,3,4,5]

print(b)

b=[1,2,3,4,5]

clonning using copy() method

a=[1,2,3,4,5]

b=a.copy()

print(b)

[1, 2, 3, 4, 5]

a is b

False

methods example description

list( ) >>> a=(1,2,3,4,5) it convert the given tuple

a=list(a) into list.

print(a)

[1, 2, 3, 4, 5]

tuple( ) >>> a=[1,2,3,4,5] it convert the given list into

a=tuple(a) tuple.

print(a)

Benefit of Tuple:

Tuples are faster than lists.

 If the user wants to protect the data from accidental changes, tuple can be used.

 

 Tuples can be used as keys in dictionaries, while lists can't.

Operations on Tuples:

  1. Indexing
  2. Slicing
  3. Concatenation
  4. Repetitions
  5. Membership
  6. Comparison

Operations examples description

Creating the tuple with

Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data

types.

print(a[0]) Accessing the item in the

Indexing 20 position 0

a[2] Accessing the item in the

60 position 2

Slicing >>>print(a[1:3]) Displaying items from 1st

(40,60) till 2nd.

Concatenation >>> b=(2,4) Adding tuple elements at

print(a+b) the end of another tuple

(20,40,60,”apple”,”ball”,2,4) elements

Repetition >>>print(b*2) repeating the tuple in n no

(2,4,2,4) of times

a=(2,3,4,5,6,7,8,9,10)

5 in a

Membership True Returns True if element is

100 in a present in tuple. Otherwise

False returns false.

2 not in a

False

a=(2,3,4,5,6,7,8,9,10)

Comparison

b=(2,3,4) Returns True if all elements

a==b in both elements are same.

False Otherwise returns false

a!=b

True

Tuple methods:

Tuple is immutable so changes cannot be done on the elements of a tuple once it is

assigned.

methods example description

a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the

a.index(5) first matched item.

a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the

a.count(3) given element.

len(tuple) >>> len(a) return the length of the

(^5) tuple

Example1: Output:

def div(a,b): enter a value:

r=a%b enter b value:

q=a//b reminder: 1

return(r,q) quotient: 1

a=eval(input("enter a value:"))

b=eval(input("enter b value:"))

r,q=div(a,b)

print("reminder:",r)

print("quotient:",q)

Example2: Output:

def min_max(a): smallest: 1

small=min(a) biggest: 6

big=max(a)

return(small,big)

a=[1,2,3,4,6]

small,big=min_max(a)

print("smallest:",small)

print("biggest:",big)

Tuple as argument:

The parameter name that begins with * gathers argument into a tuple.

Example: Output:

def printall(*args): (2, 3, 'a')

print(args)

printall(2,3,'a')

Dictionaries:

Dictionary is an unordered collection of elements. An element in dictionary has a key:

value pair.

All elements in dictionary are placed inside the curly braces i.e. { }

 Elements in Dictionaries are accessed via keys and not by their position.

 

 The values of a dictionary can be any data type.

 

 Keys must be immutable data type (numbers, strings, tuple)

Operations on dictionary:

  1. Accessing an element
  2. Update
  3. Add element
  4. Membership

setdefault(key,value) >>> a.setdefault(3,"three") If key is in the

'three' dictionary, return its

print(a) value. If key is not

{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with

a.setdefault(2) a value of dictionary and

'two' return dictionary.

a.update(dictionary) >>> b={4:"four"}

It will add the dictionary

a.update(b) with the existing print(a)

{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} dictionary

fromkeys() >>> key={"apple","ball"} It creates a dictionary

value="for kids" from key and values.

d=dict.fromkeys(key,value)

print(d)

{'apple': 'for kids', 'ball': 'for kids'}

len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of

lena(a) the list.

clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements

a.clear() form the dictionary.

print(a)

del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire

del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary

A list is mutable A tuple is immutable A dictionary is mutable

Lists are dynamic Tuples are fixed size in nature In values can be of any

data type and can

repeat, keys must be of

immutable type

List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in

brackets[ ] and their and cannot be updated curly braces { } and

elements and size consist of key:value

can be changed

Homogenous Heterogeneous Homogenous

Example: Example: Example:

List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":

Or 24}

Words = "spam", "eggs"

Access: Access: Access:

print(list[0]) print(words[0]) print(dict["ram"])

Can contain duplicate Can contain duplicate elements. Cant contain duplicate

elements Faster compared to lists keys, but can contain

duplicate values

Slicing can be done Slicing can be done Slicing can't be done

Usage: Usage: Usage:

 List is used if a

Tuple can be used when data

Dictionary is used

collection of data that cannot be changed. when a logical

doesnt need random

 A tuple is used in combination association between

access. with a dictionary i.e.a tuple might key:value pair.

 List is used when represent a key.

 When in need of fast

data can be modified lookup for data, based

frequently on a custom key.

 Dictionary is used

when data is being

constantly modified.

Advanced list processing:

List Comprehension:

 List comprehensions provide a concise way to apply operations on a list.

 

It creates a new list in which each element is the result of applying a given operation in a

list.

It consists of brackets containing an expression followed by a “for” clause, then a list.

 The list comprehension always returns a result list.

Syntax

list=[ expression for item in list if conditional ]

List Comprehension Output

L=[x**2 for x in range(0,5)] (^) [0, 1, 4, 9, 16]

print(L)

[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]

[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']

mixed=[1,2,"a",3,4.2] [1, 4, 9]

[x**2 for x in mixed if type(x)==int]

[x+3 for x in [1,2,3]] [4, 5, 6]

[x*x for x in range(5)] [0, 1, 4, 9, 16]

num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]

[x for x in num if x>=0]

str=["this","is","an","example"] ['t', 'i', 'a', 'e']

element=[word[0] for word in str]

print(element)

Illustrative programs:

Selection sort Output

a=input("Enter list:").split() Enter list:23 78 45 8 32 56

a=list(map(eval,a)) [8,2 3, 32, 45,56, 78]

for i in range(0,len(a)):

smallest = min(a[i:])

sindex= a.index(smallest)

a[i],a[sindex] = a[sindex],a[i]

print (a)

Insertion sort output

a=input("enter a list:").split()

a=list(map(int,a))

for i in a: enter a list: 8 5 7 1 9 3

j = a.index(i) [1,3,5,7,8,9]

while j>0:

if a[j-1] > a[j]:

a[j-1],a[j] = a[j],a[j-1]

else:

break

j = j- 1

print (a)

Merge sort output

def merge(a,b):

c = [] [3,9,10,27,38,43,82]

while len(a) != 0 and len(b) != 0:

if a[0] < b[0]:

c.append(a[0])

a.remove(a[0])

else:

c.append(b[0])

b.remove(b[0])

if len(a) == 0:

c=c+b

else:

c=c+a

return c

def divide(x):

if len(x) == 0 or len(x) == 1:

return x

else:

middle = len(x)//

a = divide(x[:middle])

b = divide(x[middle:])

return merge(a,b)

x=[38,27,43,3,9,82,10]

c=divide(x)

print(c)