0% found this document useful (0 votes)
45 views18 pages

Python - Basics (Unit 4)

Python has 4 built-in data types used to store collections of data: lists, tuples, sets, and dictionaries. Lists are ordered and changeable, allow duplicate elements, and use indexes to access elements. Tuples are ordered and unchangeable like lists but do not allow duplicate elements or allow item deletion. Sets are unordered collections of unique elements. Dictionaries store mappings of unique keys to values.

Uploaded by

Abdul Majeed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views18 pages

Python - Basics (Unit 4)

Python has 4 built-in data types used to store collections of data: lists, tuples, sets, and dictionaries. Lists are ordered and changeable, allow duplicate elements, and use indexes to access elements. Tuples are ordered and unchangeable like lists but do not allow duplicate elements or allow item deletion. Sets are unordered collections of unique elements. Dictionaries store mappings of unique keys to values.

Uploaded by

Abdul Majeed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Unit 4: Python Built-in Data Types

Build-in Data Types:

Python has 4 built-in data types that used to store collections of data. These are:

List

Tuple

Set

Dictionary

Python Lists:

Lists are used to store multiple items in a single variable.

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

can be of different data type.

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Example:

print (list1) # will output whole list ['apple', 'banana', 'cherry']

list2 = ['hello', 'world']

list3 = [123, 'abcd', 10.2, 'd'] #List of different data type

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.

print (len(list1)) #will output 3

- <class 'list'>

print (type(list1)) # Output <class 'list'>

print (type(list3[0])) # Output

The list() Constructor: It is also possible to use the list() constructor when creating a new list.

mylist = list (("apple", "banana", "cherry")) # note square brackets

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.

mylist = ["apple", "banana", "cherry"]

print (thislist[1]) #will output banana

print (thislist[-1]) #will output cherry

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:

list_varible (start_index : stop_index : step)

Example:

mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon"]

cherry']

print (mylist[2:]) # index 2 to -

print (mylist[:]) #Slicing the elements - ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon']

print (mylist[0:5:2]) # index 0 to 4, step2 ['apple', 'cherry', 'kiwi']

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]

print (list) # Output [1, 2, 3, 4, 5, 6]

list[2] = 10 # Assign value to the value to the second index

print (list) # Output [1, 2, 10, 4, 5, 6]

list[1:3] = [89, 78] # Updating multiple element

print (list) # Output[1, 89, 78, 4, 5, 6]

list[-1] = 25 # Update value at the end of the list

print (list) # Output [1, 89, 78, 4, 5, 25]

List Operator: Some operators working with python list are below. Suppose we have two

lists-

L1 = [1, 2, 3, 4] and L2 = [5, 6, 7, 8]

Repetition (*): Enables the list elements to be repeated multiple times.

print (L1 * 2) # Give L1 two times. [1, 2, 3, 4, 1, 2, 3, 4]

Concatenation (+): Concatenates the two lists.

print (L1 + L2) # Concatenate L1 and L2. [1, 2, 3, 4, 5, 6, 7, 8]

Membership (in): Returns true if a particular item exists in a particular list.

print (2 in L1) # True

Removing elements from List: Python provides the remove() function which is used to

remove the element from the list.

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

print (L1) # Output [1, 2, 3, 4, 5]

L1.remove(2) # It remove the second element (index 1 elements)

print (L1) # Output [1, 3, 4, 5]

Adding new elements: Python also provides append(NewElement) and insert(Index,

NewElement) methods, which can be used to add values to the list.

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

print (L1) # Output [1, 2, 3, 4, 5]

of list

print (L1) # Output [1, 2, 3, 4, 5, 6]

L1.insert(2, 7) # In insert new element 7 at index 2

print (L1) # Output [1, 2, 7, 3, 4, 5, 6]

L1.append(int(input("Enter element to add:"))) #Accept value at run time

print (L1) # Output [1, 2, 7, 3, 4, 5, 6, NewElement]

List Built-in functions:

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

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

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

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

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

Python Tuple

Tuple is used to store the sequence of immutable Python objects i.e. it used to store

multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable.

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 ordered, unchangeable, and allow duplicate values.

Tuple items are indexed like list, the first item has index [0], the second item has

index [1] etc.

Tuple items can be of any data type.

Example 1:

T1 = (101, "Peter", 22)

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

T3 = 10, 20, 30, 40, 50

print (type(T1)) # <class 'tuple'>

print (type(T2)) # <class 'tuple'>

print (type(T3)) # <class 'tuple'>

print (T1) # (101, 'Peter', 22)

print (T2) # ('Apple', 'Banana', 'Orange')

print (T3) # (10, 20, 30, 40, 50)

print (T1[0]) # 101

Example 2:

tuple = (1,2,3,4,5,6,7)

print (tuple[1:]) #element 1 to end (2, 3, 4, 5, 6, 7)

print (tuple[:4]) #element 0 to 3 element (1, 2, 3, 4)

print (tuple[1:5]) #element 1 to 4 element (2, 3, 4, 5)

print (tuple[0:6:2]) # element 0 to 6 and take step of 2 (1, 3, 5)

print (tuple[-4]) # 4th element from last 4


print (tuple[-3:-1])) # element from last 2 to 3 (5, 6)


Creating a tuple with single element is slightly different. We will need to put comma after

the element to declare the tuple.

tup1 = ("JavaTpoint") # It creates string

print (type(tup1)) # <class 'str'>

tup2 = ("JavaTpoint" ,) # Creating a tuple with single element

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) # Output (1, 2, 3, 4, 5, 6)

del tuple1[0] # Shows error

print(tuple1)

del tuple1 # Tuple tuple1 deleted

print(tuple1) # Item not found

Tuple Operator: Some operators working with python tuple like list operator

T1 = (1, 2, 3, 4, 5)

T2 = (6, 7, 8, 9)

Repetition (*):

print (T1 * 2) # Give T1 two times. (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

Concatenation (+):

print (T1 + T2) # Concatenate T1 and T2. (1, 2, 3, 4, 5, 6, 7, 8, 9)

Membership (in):

print (2 in T2) # False

Tuple Built-in functions:

cmp (tuple1, tuple2): It compares two tuples and returns true if tuple1 is greater

than tuple2 otherwise false

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

max (list): It returns the maximum element of the tuple.

min (list): It returns the minimum element of the tuple.

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

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

means we can modify it after its creation.


‫ال يوجد فهرس مرفق بعناصر املجموعة‬

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'}

print (Months) # {'May', 'April', 'January', 'March'}

print (Months) # {'May', 'April', 'January', 'March', 'February'}

print (Months) # {'May', 'April', 'January', 'March'}

print (Months) # Error

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'}

Python Set Operations:


Set can be performed mathematical operation such as union, intersection, difference, and
symmetric difference. Python provides the facility to carry out these operations with
operators or methods.
Union of two Sets: The union of the two sets contains all the items that are present in both
the sets. This can be calculated by using the or (|) operator or union() function.
Days1 = {"Sunday", "Monday","Tuesday"}
Days2 = {"Tuesday","Wednesday","Thursday"}
print (Days1 | Days2) # {'Tuesday', 'Wednesday', 'Monday', 'Sunday', 'Thursday'}
print (Days1.union(Days2)) # {'Tuesday', 'Wednesday', 'Monday', 'Sunday', 'Thursday'}

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:

MyFrozenset = frozenset ([1,2,3,4,5])


print (type(MyFrozenset))
print ("\nPrinting content of frozen set...")
for i in MyFrozenset:
print (i);
MyFrozenset.add(6) # Gives an error
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key.
It is the mutable data-structure. The dictionary is defined into element Keys and values.
Keys must be a single element. Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.
The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).
Syntax:
DictName = Value1,
Example:
Employee = {"Name": "John", "Age": 29, "Salary":25000, "Company":"AZ Group"}
print (type(Employee)) # <class 'dict'>
employee data .... ")
print (Employee) # {'Name': 'John', 'Age': 29, 'Salary': 25000, 'Company': 'AZ Group'}

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

Dictionary Built-in functions:


cmp (dict1, dict2): It compares the items of both the dictionary and returns true if
the first dictionary values are greater than the second dictionary, otherwise it returns
false.
len (dict): It is used to calculate the length of the dictionary.
str (dict): It converts the dictionary into the printable string representation.
type (variable): It is used to print the type of the passed variable
dict.clear(): It is used to delete all the items of the dictionary.
dict.copy(): It returns a shallow copy of the dictionary.
dict.fromkeys(iterable, value = None./): Create a new dictionary from the iterable
with the values equal to value.
dict.get(key, default = "None"): It is used to get the value specified for the passed
key.
dict.has_key(key): It returns true if the dictionary contains the specified key.
dict.items(): It returns all the key-value pairs as a tuple.
dict.keys(): It returns all the keys of the dictionary.
dict.setdefault(key.default = "None ): It is used to set the key to the default value if
the key is not specified in the dictionary.
dict.update(dict2): It updates the dictionary by adding the key-value pair of dict2 to
this dictionary.
dict.values(values): It returns all the values of the dictionary.

You might also like