Chap 07 Tuples Set Datetime
Chap 07 Tuples Set Datetime
● The tuple object (pronounced “toople” or “tuhple”) is roughly like a list that
cannot be changed - tuples are sequences, like lists, but they are immutable,
like strings.
● They support arbitrary types, arbitrary nesting, and the usual sequence
operations.
Creating a Tuple
A tuple can also be created without using parentheses. This is known as tuple
packing.
<class 'str'>
>>> my_tuple = ("hello",) # Creating a tuple having one element
>>> print(type(my_tuple))
<class 'tuple'>
>>> print(type(my_tuple))
<class 'tuple'>
Access Tuple Elements
○ Negative Indexing
○ Slicing
Access Tuple Elements - Indexing
>>> print(my_tuple[0])
p
>>> print(my_tuple[5])
c
t
>>> print(n_tuple[1][1]) # nested index
7
Access Tuple Elements - Negative Indexing
● The index of -1 refers to the last item, -2 to the second last item and
so on.
>>> my_tuple = ('p','t','i','t','h','c', 'm') # Accessing tuple elements using indexing
>>> print(my_tuple[-1])
m
>>> print(my_tuple[-6])
t
Access Tuple Elements - Slicing
>>> print(my_tuple[1:4])
('t', 'i', 't')
>>> print(my_tuple[:-6])
('p', 't')
>>> print(my_tuple[6:])
('c', 'm')
>>> print(my_tuple[:]) # elements beginning to end
>>> my_tuple[3][0] = 9
>>> print(my_tuple)
>>> my_tuple = ('p', 't', 'i', 't', '-', 'h', 'c', 'm') # Tuples can be reassigned
>>> print(my_tuple)
('p', 't', 'i', 't', '-', 'h', 'c', 'm')
Changing a Tuple
● Both
>>> + 2,and
print((1, 3) +*(4,
operations
5, 6)) result in a new tuple.
# Concatenation
(1, 2, 3, 4, 5, 6)
● The count() method of Tuple returns the number of times the given element
appears in the tuple.
tuple.count(element)
● The Index() method returns the first occurrence of the given element from
the tuple.
Syntax:
Parameters:
■ element: The element to be searched.
■ start (Optional): The starting index from where the searching is started
■ end (Optional): The ending index till where the searching is done
Why Tuples?
Input Output
tuple1 = (10, 20, 30, 40, 50) (50, 40, 30, 20, 10)
Solution
>>> tuple1 = (10, 20, 30, 40, 50)
>>> tuple1 = [::-1]
>>> print(tuple1)
Exercise 2: Create a tuple with single item 50
Solution
>>> tuple1 = (50,)
Exercise 4: Unpack the tuple into 4 variables
Input Output
tuple1 = (10, 20, 30, 40) tuple1 = (10, 20, 30, 40)
# Your code
print(a) # should print 10
print(b) # should print 20
print(c) # should
print 30 print(d) # should print 40
Solution
>>> tuple1 = (10, 20, 30, 40)
>>> a, b, c, d =tuple1
>>> print(a)
>>> print(b)
>>> print(c)
>>> print(d)
13. Python - Set
13. Python - Set
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4}
Creating an empty set is a bit tricky.
<class 'dict'>
<class ‘set'>
Modifying a set in Python
● The update() method can take tuples, lists, strings or other sets
as its argument. In all cases, duplicates are avoided.
Modifying a set in Python
>>> my_set = {1, 2, 5} # initialize a with {}
>>> print(my_set)
{1, 2, 5}
{1, 2, 3, 5}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
>>> print(my_set)
{1, 3, 5}
>>> my_set.discard(2)
>>> print(my_set)
{1, 3, 5}
>>> my_set.remove(2)
● Remove all the items from a set using the clear() method.
>>> my_set = set("PTITHCM")
>>> print(my_set)
'P'
>>> print(my_set)
● Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this
with operators or methods.
union difference
>>> A.union(B)
1 2
{1, 3, 4, 5, 6, 7, 8} 4 6 7
A 3 B
>>> B.union(A) 5 8
{1, 3, 4, 5, 6, 7, 8}
Set Union
● Intersection of A and B is a set of elements that are common in both the sets.
>>> A.intersection(B)
1 2
{4, 5,} 4 6 7
A 3 B
>>> B. intersection(A) 5 8
{4, 5,}
Set Difference
● Difference of the set B from set A(A - B) is a set of elements that are only in A but not
in B. Similarly, B - A is a set of elements in B but not in A.
>>> A.difference(B)
1 2
{1, 2, 3} 4 6 7
A 3 B
>>> B. difference(A) 5 8
{8, 6, 7}
Set Symmetric Difference
● Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
● Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
>>> A.symmetric_difference(B)
1 2
{1, 2, 3, 6, 7, 8} 4 6 7
A 3 B
>>> B. symmetric_difference(A) 5 8
{1, 2, 3, 6, 7, 8}
Other Python Set Methods
Method Description
update() Updates the set with the union of itself and others
Built-in Functions with Set
● Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of
enumerate()
the set as a pair.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
● Given two lists, find the missing and additional values in both the
lists.
● Input :
○ list1 = [1, 2, 3, 4, 5, 6]
○ list2 = [4, 5, 6, 7, 8]
● Output :
○ Missing values in list1 = [8, 7]
● Two strings are given and you have to modify 1st string such
that all the common characters of the 2nd string have to be
removed and the uncommon characters of the 2nd string have
to be concatenated with uncommon characters of the 1st string.
● Output : "cbgf"
● Output : "bsxz"
Differences and Applications of List, Tuple, Set and Dictionary
in Python
● Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in
Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.
● Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar
to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are
mutable.
● Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements.
Python’s set class represents the mathematical notion of a set.
● Dictionary: in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data
values, used to store data values like a map, which, unlike other Data Types that hold only a single
value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make
it more optimized.
● List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the
data in an efficient manner.
Differences and Applications of List, Tuple, Set and Dictionary
in Python
List Tuple Set Dictionary
List is a non- Tuple is also a non- Set data structure is Dictionary is also a
homogeneous data homogeneous data also non- non-homogeneous
structure that stores structure that stores homogeneous data data structure which
the elements in single single row and multiple structure but stores in stores key value pairs
row and multiple rows rows and columns single row
and columns
List can be represented Tuple can be Set can be represented Dictionary can be
by [ ] represented by ( ) by { } represented by { }
List can use nested Tuple can use nested Set can use nested Dictionary can use
among all among all among all nested among all
Differences and Applications of List, Tuple, Set and Dictionary
in Python
List Tuple Set Dictionary
List can be created Tuple can be created Set can be created Dictionary can be
using list() function using tuple() function. using set() function created
using dict() function.
List is mutable i.e we Tuple is immutable i.e Set is mutable i.e we Dictionary is mutable.
can make any changes we can not make any can make any changes But Keys are not
in list. changes in tuple in set. But elements duplicated.
are not duplicated.
● List:
○ Used in JSON format
○ Used in Databases
● Tuple:
○ Used to insert records in the database through SQL query at a time.Ex:
(1.’sravan’, 34).(2.’geek’, 35)
● Set:
○ Finding unique elements
○ Join operations
● Dictionary:
○ Used to create a data frame with lists
○ Used in JSON
Python – Date and Time
Python datetime module
● In Python, date and time are not a data type of their own, but a
module named datetime can be imported to work with the date as
well as time. Python Datetime module comes built into Python, so
there is no need to install it externally.
● Python Datetime module supplies classes to work with date and time.
These classes provide a number of functions to deal with dates, times
and time intervals. Date and datetime are an object in Python, so
when you manipulate them, you are actually manipulating objects and
not string or timestamps.
The DateTime module is categorized into 6 main classes
● date – An idealized naive date, assuming the current Gregorian calendar always
was, and always will be, in effect. Its attributes are year, month and day.
● time – An idealized time, independent of any particular day, assuming that every
day has exactly 24*60*60 seconds. Its attributes are hour, minute, second,
microsecond, and tzinfo.
● datetime – Its a combination of date and time along with the attributes year,
month, day, hour, minute, second, microsecond, and tzinfo.
● timezone – A class that implements the tzinfo abstract base class as a fixed offset
from the UTC (New in version 3.2).
Date class
● Constructor syntax:
○ class datetime.date(year, month, day)
○ 1 <= day <= number of days in the given month and year
Example 1: Date object representing date in Python
>>> from datetime import date #import date class
>>> my_date = date(2022, 12, 11)
>>> print("Date passed as argument is", my_date)
Date passed as argument is 2022-12-11
● We can get the year, month, and date attributes from the date object using the
method.
● The timestamp is the number of seconds from 1st January 1970 at UTC to a
particular date.