Unit 3
Data Structures in Python
Content:
List: Basic list operations, built in list functions
Tuples: Tuple operations, functions
Sets: set operations, set functions
Dictionary: Dictionary operations and functions
List:
Lists are just like array, declared in other programming.
List need not be homogeneous always which makes it
more powerful tool.
A list may contain data types like integers, strings as well
as any objects.
Lists are mutable, they can appended and updated even
after its creation.
The element in a list are indexed according to a definite
sequence and indexing of a list is done with 0 being first
index.
Declaring a list/Creating List/ Defining List:
In Python programming, a list is created by placing all the
items (elements) inside square brackets [], separated by
commas.
It can have any number of items and they may be of
different types (integer, float, string etc.).
Example:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
A list can also have another list as an item. This is called a
nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Access List Elements:
There are various ways in which we can access the elements of
a list.
List Index:
We can use the index operator [] to access an item in a list.
In Python, indices start at 0. So, a list having 5 elements will
have an index from 0 to 4.
Trying to access indexes other than these will raise an Index
Error. The index must be an integer.
Ex: Print (list[5]) #index error
We can't use float or other types, this will result in Type Error.
Ex: print (list[2.3]) # Type error
Negative List Indexing:
Python allows negative indexing to its elements.
If index number of first element is 0, then index number of
last element should be -1, second last should be at index -
2, and so on.
Example: list = [10, 20, 30, 40]
Index 0 = 10
Index -1 = 40
Index -2 = 30
Iterating through List using loop:
The list element can be iterated using loops in
python.
The elements in list can access sequentially
using loop.
We can iterate the list using for-loop and while
loop.
Slicing Lists (Using slicing operator ( : ) on
lists:
To print the specific range of elements of a list, we use slicing
operations.
The slice operation is performed on list with the use of colon
(:)
1) To print the element from beginning to a range,
use syntax [:index]
2) To print the element from end,
use syntax [: - index]
3) To print the element from specific index till the end, use
syntax
[index:]
4) To print the element within a index, use syntax
[start_index : end_index]
5) To print the whole list with slicing operator,
use syntax [ : ]
6) To print the whole list in reverse order,
use syntax [ : : -1]
Basic List Operations:
1) Adding element : append(), insert() and extend()
functions:
We know that, a list is mutable and updatable entity.
After creating a list we can use the three functions append(),
insert() and extend() to add new elements in it.
1) append()
This function appends or adds specified element to list.
It adds specified element to the last position of list.
Syntax:
list_name.append(new_element)
2) insert()
This function insert an element at the specified
position in the list.
Syntax:
list_name.insert(index, element)
Example:
list = [1,2,3]
list.insert(1, 8)
3) extend()
This function adds elements of parameter list with
invoking list.
Syntax:
list_name.extend(another_list)
Example:
list1 = [1,2,3]
list2 = [10,20,30]
list1.extend(list2)
print(list1)
[1,2,3,10,20,30]
2) Updating element: Using assignment operator (=)
to over-write value:
We can update and over-write element by using
assignment operator(=).
Simply use the assignment operator to update
value at required index.
Syntax:
list_name[index] = new_element
3) Delete or Remove element from list:
We can delete one or more elements from list by using
‘del’ keyword or using remove() function or using pop() or
clear() function.
1) del:
del keyword is to remove one or more element from list
and even it can remove entire list.
Syntax:
del list_name[index]
2) remove():
This function removes specified element from a list.
Syntax:
list_name.remove(element)
3) pop():
This function removes element from specified index.
Syntax:
list_name.pop(index_number)
4) clear():
This function removes all element from a
list.
Syntax:
list_name.clear()
Built-in List Functions:
Tuples:
A tuple is a collection of objects which is ordered and
immutable.
Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-
separated values.
Declaring a tuple/Creating tuple/ Defining
tuple :
In Python programming, a tuple is created by placing all
the items (elements) inside parenthesis ( ), separated by
commas.
It can have any number of items and they may be of
different types (integer, float, string etc.).
Example:
# empty tuple
my_ tuple = ( )
#Tuple of integers
my_tuple = (1, 2, 3)
# tuple with mixed data types
my_tuple = (1, "Hello", 3.4)
Tuple cannot contain a single element in it.
That means tuple may empty or it have minimum two
elements in it.
Accessing Tuple Elements:
There are various ways in which we can access the
elements of a list.
List Index:
We can use the index operator [] to access an item in a
tuple.
In Python, indices start at 0. So, a list having 5 elements
will have an index from 0 to 4.
Ex: tuple = (1,2,3,4,5)
print(tuple[1])
Negative tuple Indexing:
Python allows negative indexing to its elements.
If index number of first element is 0, then index number of
last element should be -1, second last should be at index
-2, and so on.
Example: tuple = (10, 20, 30, 40)
Index 0 = 10
Index -1 = 40
Index -2 = 30
Slicing tuple (Using slicing operator ( : ) on
tuple :
To print the specific range of elements of a tuple, we use
slicing operations.
The slice operation is performed on tuple with the use of
colon ( : )
1) To print the element from beginning to a range,
use syntax [:index]
2) To print the element from end,
use syntax [: - index]
3) To print the element from specific index till the end, use
syntax
[index:]
4) To print the element within a index, use syntax
[start_index : end_index]
5) To print the whole tuple with slicing operator,
use syntax [ : ]
6) To print the whole tuple in reverse order,
use syntax [ : : -1]
Basic Tuple Operations:
1) Tuples are immutable:
It means, we cannot modify tuple elements, once they are
initialized and created.
It will show type error.
Even tuple does not have append() function any other
modification related function to change or update tuple
elements.
Syntax: Tuple = tuple + (element)
Ex. tuple = tuple + ( 5,7)
Finding length of tuples:
Tuple’s built in function len() returns length of tuple.
Length is the total number of elements in tuple.
syntax for len() method −
len(tuple)
tuple − This is a tuple for which number of elements to
be counted.
Testing membership operators on tuples:
We know that, the membership operator are in and not
in.
If the element is in the tuple the in operator return a True
value.
If the element is not in the tuple the in operator return a
False value.
Syntax: Print(“element” in tuple)
print(“element” not in tuple)
Concatenation of Tuple:
Tuple can be concatenated by using concatenation operator
(+).
tuple 1 = (1,2,3,4)
tuple 2 = (10,20,30)
tuple 3 = tuple1 + tuple2
Print(tuple3)
The elements of tuple 2 is added to element of tuple1 and
initialized to tuple 3.
Suppose if you write tuple4 = tuple1, tuple2
This will create nested tuple which contains tuple1 at index
0 and tuple 2 at index 1
Multiplying Tuple:
Multiplying a tuple by an integer x will simply return a new
tuple with all the elements from the first tuple being
repeated x number of times.
Example: tuple = (10,20,30)
tuple2 = tuple * 3
print( tuple2)
Deleting Tuple:
We can delete an entire tuple, if it is no more
required.
It is done by using keyword del followed by
tuple name.
Syntax:
del tuple_name
Set:
Sets are used to store multiple items in a single variable.
Set is one of the built-in data types in Python used to store collections of
data.
A set is a collection which both unordered and unindexed.
Sets are written with curly brackets.
Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the set must be
of immutable type.
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
Declaring set Or Defining Set Or Creating
Set:
Simple Set Declaration:
Set1 = {10,20,30}
print(set1)
The set contains only immutable types, so here is the set
which contains tuple and string:
Set2 = {12, “hello”, (1,2,3)}
print(set2)
But we can’t add a list to the set because list is the
mutable type.
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python.
To make a set without any elements, we use the set() function
without any argument.
Set = { }
This will create a empty dictionary.
A = set ({ })
This above statement will create a empty set.
type()
From Python's perspective, sets are defined as objects with the
data type 'set'
Access Items of Set:
You cannot access items in a set by referring to an index or a
key.
Set is not subscriptable, or set object does not support
indexing.
But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword.
Iterating through Set using for-loop:
A set does not support indexing, but it can be iterated
using for-loop.
For example:
set1 = set({10,20,30})
for i in set1:
print(i)
Basic Set Operations:
1) Adding element: update() and add() functions:
Add() function:
Once a set is created, you cannot change its items, but you
can add new items.
To add one item to a set use the add() method.
set = {"apple", "banana", "cherry"}
set.add("orange")
print(“new set=“,set)
Update() function:
The update() method updates the current set, by adding
items from another set (or any other iterable).
If an item is present in both sets, only one appearance of this
item will be present in the updated set.
Syntax
set.update(set)
The single argument can be a set, list, tuples or a dictionary.
It automatically converts into a set and adds to the set.
Length of set:
The len() function returns the number of items in an object.
When the object is a string, the len() function returns the
number of characters in the string
Syntax
len(object)
An object. Must be a sequence or a collection.
Removing Element: discard(), remove(),
pop() and clear() functions :
A particular item can be removed from set using functions,
discard() and remove().
1)discard():
While using discard() if the item does not exist in the set, it
remains unchanged.
Syntax:
set.discard(element)
2) remove():
The remove() method removes the specified element from
the set.
Syntax:
set.remove(element)
3) Pop():
We can remove and return an item using the pop()
function.
Set being unordered, there is no way of determining
which item will be popped.
The pop() method removes a random item from the set.
Syntax:
set.pop()
4) Clear()
We can also remove all items from a set using clear().
Syntax:
set.clear()
Set Union/ Join two set:
You can use the union() method that returns a new set
containing all items from both sets,
or the update() method that inserts all the items from one set
into another.
Union is performed using a pipe operator(|).
Syntax:
set3 = set1 | set2
OR
set3 = set1.union(set2)
Set Intersection:
Intersection of A and B is a set of elements that are
common in both sets.
The intersection is performed using ampersand (&)
operator.
Also can be performed using function intersection().
Syntax:
c=A&B
OR
C = A.intersection(B)
Set Difference:
Difference of A and B i.e. (A-B) is a set of elements that are
only in A but not in B.
Similarly, B –A is a set of element in B but not in A.
The difference operator performed using (- ) operator.
Same can be performed using difference() function.
Syntax:
C = A - B OR A.difference(B)
C = B – A OR B.difference(A)
Set Symmetric difference:
Symmetric difference of A and B is a set of elements in
both A and B except those that are common in both.
The symmetric diffrence is performed using (^) operator.
Same can be accomplished using the function
symmetric_diffrence().
Syntax:
C = A^B
OR A.symmetric_difference(B)
Delete Set:
Similar to list and tuple, if you want to delete entire set.
You can delete the set using a del keyword followed by
set name to be deleted.
Syntax:
del set
Dictionaries:
Python dictionary is an unordered collection of items.
Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key
is known.
Creating Python Dictionary:
Creating a dictionary is as simple as placing items inside curly
braces {} separated by commas.
An item has a key and a corresponding value that is expressed
as a pair (key: value).
While the values can be of any data type and can repeat, keys
must be of immutable type (string, number or tuple with
immutable elements) and must be unique.
Dict1 = { } # empty dictionary
Dict2 = {1: “red”, 2: “blue”} # dict with integer keys
Dict3 = { “name”: “abc”, 1:[1,2,3]} # dict with mixed keys
Dict4 = dict([(1, “red”), (2, “blue”)]) #from seq having each item as
a pair
Accessing Dictionary elements using index
numbers:
Elements/values of a dictionary are accessible only when
keys/indexes are known.
Similar to list and tuple, elements of dictionary are
accessible by referring its index number inside index
operator([ ] ).
You can also access the elements using for-loop.
The Keys() and values() functions:
Dictionary provides two built-in functions, keys() and
values().
The keys function will return the keys in dictionary.
Whereas, values() function will return a values.
Syntax:
dict.keys()
dict.values()
Basic Dictionary operations:
1) Change or update elements in dictionary: Update()
function
Dictionary allows to change or update and add an
key:value pair, by using update() function.
If key is already present in dictionary, the value gets
updated, else a new key:value pair is added to the
dictionary.
Syntax:
dict.update(1:”abc”)
Length of the dictionary:
The len() function returns the number of items in an
object.
When the object is a string, the len() function returns
the number of characters in the string
Syntax
len(object)
An object. Must be a sequence or a collection.
Update dictionary: Using assignment operator(=)
to over=write value:
A dictionary is mutable entity.
We can add new item or change the value of existing item
using assignment operator.
Syntax:
dict[key]=value
If you want to update new item the key should be new and
assign the value to the key.
If you want to over-write the value the key should be
existing in your dictionary.
Remove element: pop(), popitem() and clear()
functions:
Dictionary allows to remove elements using the four ways,
like, del keyword, pop(), popitem() and clear() functions.
1) Del keyword:
Keyword del will remove key-value pair of specified key.
If any key is invalid or unavailable it will show a keyerror.
It can also delete the entire dictionary.
Syntax:
del dict[“key”]
2) pop() function:
The pop() function will remove key-value pair of specified key.
Syntax:
dict.pop(“key”)
3) popitem() function:
The popitem() function remove any random key-value pair from
dictionary.
Syntax: dict.popitem()
4) clear():
The clear() function will remove all elements form the dictionary.
Syntax: dict.clear()