Python - Basics (Unit 4)
Python - Basics (Unit 4)
Python has 4 built-in data types that used to store collections of data. These are:
List
Tuple
Set
Dictionary
Python Lists:
A list contains items separated by commas and enclosed within square brackets [].
Lists are almost similar to arrays in C. One difference is that all the items belonging to a list
List items are indexed, the first item has index [0], the second item has index [1] etc.
Example:
print (list3) #will output whole list. [123, 'abcd', 10.2, 'd']
List length: To determine how many items a list has, use the len() function.
- <class 'list'>
The list() Constructor: It is also possible to use the list() constructor when creating a new list.
Access Items: List items are indexed and you can access them by referring to the index
number. Index start from 0. Negative indexing means start from the end.
Range of Indexes: We can specify a range of indexes by specifying start and end index. By
leaving out the start value, the range will start at the first item. By leaving out the end value,
the range will go on to the end of the list. We can get the sub-list of the list using the
following syntax.
Syntax:
Example:
cherry']
print (mylist[:]) #Slicing the elements - ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon']
Updating List Items: Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and assignment operator.
Example:
list = [1, 2, 3, 4, 5, 6]
List Operator: Some operators working with python list are below. Suppose we have two
lists-
Removing elements from List: Python provides the remove() function which is used to
L1 = [1, 2, 3, 4, 5]
L1 = [1, 2, 3, 4, 5]
of list
Python Tuple
Tuple is used to store the sequence of immutable Python objects i.e. it used to store
A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use.
Tuple items are indexed like list, the first item has index [0], the second item has
Example 1:
Example 2:
tuple = (1,2,3,4,5,6,7)
Creating a tuple with single element is slightly different. We will need to put comma after
print (type(tup2))
Deleting Tuple: Unlike lists, the tuple items cannot 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.
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
Tuple Operator: Some operators working with python tuple like list operator
T1 = (1, 2, 3, 4, 5)
T2 = (6, 7, 8, 9)
Repetition (*):
Concatenation (+):
Membership (in):
cmp (tuple1, tuple2): It compares two tuples and returns true if tuple1 is greater
Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
Unlike other collections in Python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print them
all together, or we can get the list of elements by looping through the set.
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by the
passed sequence.
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print (Days)
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"])
print (Days)
myset = {1, 2, 4, 4, 5, 8, 9, 9, 10}
print (myset) # Remove duplicate {1, 2, 4, 5, 8, 9, 10}
It can contain any type of element such as integer, float, tuple etc. But mutable elements
(list, dictionary, set) can't be a member of set.
Example:
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print (type(set1)) # <class 'set'>
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print (type(set2)) # Error
Creating empty set: Creating an empty set is a bit different because empty curly {} braces are
also used to create a dictionary as well. So Python provides the set() method used without
an argument to create an empty set.
Example:
set3 = {} # Empty curly braces will create dictionary
print (type(set3)) # Output <class 'dict'>
set4 = set() # Empty set using set() function
print (type(set4)) # Output <class 'set'>
Adding items to the set: Python provides the add() method and update() method which can
be used to add some particular item to the set. The add() method is used to add a single
element whereas the update() method is used to add multiple elements to the set.
Example:
Months = {"January", "February", "March"} # Creating set
Months = set(["January", "February", "March"]) # Creating set using fn
print (Months) # {'January', 'March', 'February'}
Months.add ("April")
print (Months) # {'January', 'April', 'March', 'February'}
Months.update (["May", "June"])
print (Months) # {'May', 'February', 'March', 'April', 'January', 'June'}
Removing items from the set: Python provides the discard() method and remove() method
which can be used to remove the items from the set. The difference between these function,
using discard() function if the item does not exist in the set then the set remain unchanged
whereas remove() method will through an error.
Example:
Months = {"January", "February", "Ma
print (Months) # {'May', 'April', 'January', 'March', 'February'}
print (Months) # {'May', 'April', 'January', 'March'}
We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element will
be popped from set.
Months = {"January", "February", "March", "April", "May"}
Months.pop()
print (Months) # {'April', 'January', 'May', 'February'}
Intersection of two sets: The intersection of the two sets is given as the set of the elements
that common in both sets. The intersection of two sets can be performed by the and
(&) operator or the intersection() function.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print (Days1 & Days2) # {'Tuesday'}
print (Days1.intersection(Days2)) # {'Tuesday'}
The intersection_update() method removes the items from the original set that are not
present in both the sets
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print (a) # {'castle'}
Difference between the two sets: The difference of two sets can be calculated by using the
subtraction (-) operator or intersection() method.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print (Days1 - Days2) # {'Thursday', 'Wednesday'}
print (Days1.difference(Days2)) # {'Thursday', 'Wednesday'}
Symmetric Difference of two sets: Symmetric difference of sets, it removes that element
which is present in both sets. It is calculated by ^ operator or
symmetric_difference() method.
a = {1, 2, 3, 4, 5, 6}
b = {1, 2, 9, 8, 10}
c=a^b # ^ operator
print(c) # {3, 4, 5, 6, 8, 9, 10}
d = a.symmetric_difference(b) # symmetric_difference() method
print(d) # {3, 4, 5, 6, 8, 9, 10}
Set comparisons: Python allows us to use the comparison operators i.e., <, >, <=, >= , == with
the sets by using which we can check whether a set is a subset, superset, or equivalent to
other set. The boolean true or false is returned.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
print (Days1 > Days2) # Days1 is the superset of Days2 hence it return true.
print (Days1 < Days2) # Prints false since Days1 is not the subset of Days2
print (Days2 == Days3) #Prints false since Days2 and Days3 are not equal
FrozenSets:
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is
passed into this method which is converted into the frozen set as a return type of the
method.
Example:
Function dict() method which is also used to create dictionary. The empty curly braces {} is
used to create empty dictionary.
Example:
# Creating an empty dictionary
Dict ={}
print (Dict) # {}
# Creating a dictionary with dict() method
Dict = dict ({1: 'Java', 2: 'T', 3:'Point'})
print (Dict) # {1: 'Java', 2: 'T', 3: 'Point'}
# Creating a dictionary with each item as a pair
Dict = dict ([(1, 'Devansh'), (2, 'Sharma')])
print (Dict)
Accessing the dictionary values: The values can be accessed in the dictionary by using the
keys as keys are unique in the dictionary.
Example:
Employee = {"Name": "John", "Age": 29, "Salary":25000, "Company":"AZ Group"}
print ("Printing employee data .... ")
print ("Name : %s" %Employee["Name"]) # Name : John
print ("Age : %d" %Employee["Age"]) # Age : 29
print ("Salary : %d" %Employee["Salary"]) # Salary : 25000
print ("Company : %s" %Employee["Company"]) # Company : AZ Group
Adding dictionary values: The value can be updated along with key Dict[key] = value. The
update() method is also used to update an existing value.
Example 1:
# Creating an empty dictionary
Dict = {}
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print (Dict)
# Adding set of values with a single key.
Dict['Ages'] = 20, 33, 24
print (Dict) # {0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Ages': (20, 33, 24)}
# Updating existing Key's Value
Dict[3] = 'Ahmed'
print (Dict) # {0: 'Peter', 2: 'Joseph', 3: 'Ahmed', 'Ages': (20, 33, 24)}
Example 2:
Employee = {}
print ("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["Salary"] = int(input("Salary: "));
Employee["Company"] = input("Company: ");
print ("Employee detail: ");
print(Employee);
Deleting elements: The items of the dictionary can be deleted by using the del keyword.
The pop() method accepts the key as an argument and remove the associated value.
Example 1:
Employee = {"Name": "John", "Age": 29, "Salary":25000, "Company":"AZ Group"}
del Employee["Company"] # Deleting Company
print (Employee) # {'Name': 'John', 'Age': 29, 'Salary': 25000}
Employee.pop("Salary") # Deleting Salary
print (Employee) # {'Name': 'John', 'Age': 29}
del Employee # Deleting complete dictionary Employee
print (Employee) # Error - name 'Employee' is not defined