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

Unit 3

1. The document discusses Python lists and tuples, which are data structures used to store ordered sequences of values. 2. Lists are mutable, meaning their values can be changed, while tuples are immutable and cannot be modified after creation. 3. Common operations on lists and tuples include accessing elements by index, slicing, concatenation, repetition, checking membership, iteration, and using built-in functions like len() to determine length.

Uploaded by

Tejas Bhagit
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)
53 views

Unit 3

1. The document discusses Python lists and tuples, which are data structures used to store ordered sequences of values. 2. Lists are mutable, meaning their values can be changed, while tuples are immutable and cannot be modified after creation. 3. Common operations on lists and tuples include accessing elements by index, slicing, concatenation, repetition, checking membership, iteration, and using built-in functions like len() to determine length.

Uploaded by

Tejas Bhagit
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/ 15

CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

UNIT 3: DATA STRUCTURES IN PYTHON

Python List

 List in python is implemented to store the sequence of various type of data


 A list can be defined as a collection of values or items of different types.
 The items in the list are separated with the comma (,) and enclosed with the square brackets [].

A list can be defined as follows.

1. L1 = ["MMP", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]
3. L3 = [1, "GAD"]

Accessing List

The elements of the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1.

The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and
so on.

Consider the following example.

Updating List values

Lists are the most versatile data structures in python since they are immutable and their values can be updated by
using the slice and assignment operator.

List = [1, 2, 3, 4, 5, 6]

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

print(List)

Output :[1, 2, 3, 4, 5, 6]

List[2] = 10;
print(List)

Output: [1, 2, 10, 4, 5, 6]

List[1:3] = [89, 78]


print(List)

Output : [1, 89, 78, 4, 5, 6]

Deleting List values

The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we
do not know which element is to be deleted from the list.

Consider the following example to delete the list elements.

List = [0,1,2,3,4]
print(List)

Output:

[0, 1, 2, 3, 4]

del List[0]
print(List)

Output:

[1, 2, 3, 4]

del List[3]
print(List)

Output:

[1, 2, 3]

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

Python List Built-in functions

Python provides the following built-in functions which can be used with the lists.

SN Function Description

1 cmp(list1, list2) It compares the elements of both the lists.

2 len(list) It is used to calculate the length of the list.

3 max(list) It returns the maximum element of the list.

4 min(list) It returns the minimum element of the list.

5 list(seq) It converts any sequence to the list.

Python List Operations

The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.

Consider a List l1 = [1, 2, 3, 4] and l2 = [5, 6, 7, 8]

Operator Description Example

Repetition The repetition operator enables the list elements to be repeated L1*2 = [1, 2, 3, 4, 1, 2,
multiple times. 3, 4]

Concatenation It concatenates the list mentioned on either side of the operator. l1+l2 = [1, 2, 3, 4, 5, 6,
7, 8]

Membership It returns true if a particular item exists in a particular list print(2 in l1) prints
otherwise false. True.

Iteration The for loop is used to iterate over the list elements. for i in l1:

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

print(i)
Output

1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Python Tuple

 Python Tuple is used to store the sequence of immutable python objects.


 Tuple is immutable and the value of the items stored in the tuple cannot be changed.
 A tuple can be written as the collection of comma-separated values enclosed with the small brackets.

Where use tuple

Using tuple instead of list is used in the following scenario.

1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.

2. Tuple can simulate dictionary without keys. Consider the following nested structure which can be used as a
dictionary.

[(101, "CO", 22), (102, "ME", 28), (103, "AE", 30)]

3. Tuple can be used as the key inside dictionary due to its immutable nature.

A tuple can be defined as follows.

T1 = (101, "Ayush", 22)


T2 = ("Apple", "Banana", "Orange")

Accessing tuple

The indexing in the tuple starts from 0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the slice operator. Python also allows us to use the colon operator
to access multiple items in the tuple.

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

The tuple items can not be deleted by using the del keyword as tuples are immutable. To delete an entire tuple,
we can use the del keyword with the tuple name

Consider the following example.

tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1
print(tuple1)

Output:

(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined

Basic Tuple operations

The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the
list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

Repetition The repetition operator enables the tuple elements to be repeated T1*2 = (1, 2, 3, 4, 5, 1, 2,
multiple times. 3, 4, 5)

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

Concatenation It concatenates the tuple mentioned on either side of the T1+T2 = (1, 2, 3, 4, 5, 6, 7,
operator. 8, 9)

Membership It returns true if a particular item exists in the tuple otherwise print (2 in T1) prints True.
false.

Iteration The for loop is used to iterate over the tuple elements. for i in T1:
print(i)
Output

1
2
3
4
5

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise
tuple2) false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple.

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

List VS Tuple

SN List Tuple

1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().

2 The List is mutable. The tuple is immutable.

3 The List has the variable length. The tuple has the fixed length.

4 The list provides more functionality than tuple. The tuple provides less functionality than the list.

5 The list Is used in the scenario in which we need The tuple is used in the cases where we need to store
to store the simple collections with no the read-only collections i.e., the value of the items can
constraints where the value of the items can be not be changed. It can be used as the key inside the
changed. dictionary.

Python Set

Unordered collection of various items enclosed within the curly braces.

The elements of the set can not be duplicate.

The elements of the python set must be immutable.

Creating a set

Example 1: using curly braces


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))

Output:

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>

Example 2: using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)

Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}

Accessing set values


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print("the set elements ... ")
for i in Days:
print(i)

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Removing items from the set

Following methods used to remove the items from the set

1. discard
2. remove
3. pop

 discard() method

Python provides discard() method which can be used to remove the items from the set.

Months = set(["January","February", "March", "April", "May", "June"])


print("\nRemoving some months from the set...");
Months.discard("January");

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

Months.discard("May");
print("\nPrinting the modified set...");
print(Months)
output:
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}

 remove() method

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

output:
{"apple”, "cherry"}

 pop() method

the pop(), method to remove an item, but this method will remove the last item. Remember that sets are
unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.

Example

Remove the last item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

output:
apple
{'cherry', 'banana'}

delete the set

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)
output:
File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set no longer exists
NameError: name 'thisset' is not defined

Difference between discard() and remove()

If the key to be deleted from the set using discard() doesn't exist in the set, the python will not give the error. The
program maintains its control flow.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the python will
give the error.

Adding items to the set

 add() method
 update() method.

Python provides the add() method which can be used to add some particular item to the set.
Months = set(["January","February", "March", "April", "May", "June"])
Months.add("July");
Months.add("August");
print(Months)
output:
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

Months = set(["January","February", "March", "April", "May", "June"])


Months.update(["July","August","September","October"]);
print(Months)
output:
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}

Python set operations (union, intersection, difference and symmetric difference)

In Python, below quick operands can be used for different operations.


| for union.
& for intersection.

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

– for difference
^ for symmetric difference

A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};

# union
print("Union :", A | B)

# intersection
print("Intersection :", A & B)

# difference
print("Difference :", A - B)

# symmetric difference
print("Symmetric difference :", A ^ B)
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with set
to perform different tasks.

Function Description

all() Return True if all elements of the set are true (or if the set is empty).

any() Return True if any element of the set is true. If the set is empty, return False.

enumerate() Return an enumerate object. It contains the index and value of all the items of set as a pair.

len() Return the length (the number of items) in the set.

max() Return the largest item in the set.

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

min() Return the smallest item in the set.

sorted() Return a new sorted list from elements in the set(does not sort the set itself).

sum() Retrun the sum of all elements in the set.

Dictionary

Dictionary is used to implement the key-value pair in python.

The keys are the immutable python object, i.e., Numbers, string or tuple.

Creating the dictionary

The dictionary can be created by using multiple key-value pairs enclosed with the small brackets () and separated
by the colon (:).

The collections of the key-value pairs are enclosed within the curly braces {}.

The syntax to define the dictionary is given below.

Dict = {"Name": "Ayush","Age": 22}

Accessing the dictionary values

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(Employee)
output:
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

The dictionary values can be accessed in the following way:

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

print("printing Employee data .... ")


print("Name :",Employee["Name"])
print("Age : ",Employee["Age"])
print("Salary : ",Employee["salary"])
print("Company : ", Employee["Company"])
Updating dictionary values

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

Dictionary is mutable. We can add new items or change the value of existing items using assignment operator.

If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

my_dict = {'name':'MMP', 'age': 26}

# update value
my_dict['age'] = 27
print(my_dict)
Output: {'age': 27, 'name': 'MMP'}

# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output: {'address': 'Downtown', 'age': 27, 'name': 'MMP'}

Deleting elements using del keyword

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)

Output:

printing the modified information


{'Age': 29, 'salary': 25000}

Dictionary Operations
Below is a list of common dictionary operations:

 create an empty dictionary

x = {}

 create a three items dictionary

x = {"one":1, "two":2, "three":3}

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

 access an element

x['two']

 get a list of all the keys

x.keys()

 get a list of all the values

x.values()

 add an entry
 x["four"]=4

 change an entry

x["one"] = "uno"

 delete an entry

del x["four"]

 remove all items

x.clear()

 number of items

z = len(x)

MM Polytechnic,Thergaon Pune
CO: PERFORM OPERATIONS ON DATA STRUCTURES IN PYTHON

 looping over keys

for item in x.keys(): print item

 looping over values

for item in x.values(): print item

Built-in Dictionary functions

The built-in python dictionary methods along with the description are given below.

SN Function Description

1 cmp(dict1, It compares the items of both the dictionary and returns true if
dict2) the first dictionary values are greater than the second
dictionary, otherwise it returns false.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string


representation.

4 type(variable) It is used to print the type of the passed variable.

MM Polytechnic,Thergaon Pune

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy