Python 2
Python 2
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial, we will
discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the 0's
and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the
collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
1. str = "Hi Python !"
1. print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the character
data-type; instead, a single character written as 'p' is treated as the string of length 1.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed as
given in the below figure.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use
the : (colon) operator in Python to access the substring from the given string. Consider the following example.
,
we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO' is given, then
str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
# Given String
str = "welcome"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item
assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are
immutable in Python.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
However, in example 1, the string str can be assigned completely to a new content as specified in the following
example.
Example 2
str = "HELLO"
print(str)
str = "hello"
print(str)
str = "welcome"
del str[1]
str1 = "welcome"
del str1
print(str1)
String Operators
Operato Description
r
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to print
the actual meaning of escape characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how formatting is
done in python.
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Next →← Prev
Python List
A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can
modify its element after it created. However, Python consists of six data-types that are capable to store the
sequences, but the most common and reliable type is the list.
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 [].
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
IIf we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
print(type(L1))
print(type(L2))
Characteristics of Lists
Let's check the first statement that lists are the ordered.
a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b
Both lists have consisted of the same elements, but the second list changed the index position of the 5th element that
violates the order of lists. When compare both lists it returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of objects.
a = [1, 2,"Peter", 4.50,"Ricky",5, 6]
b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b
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.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices are
counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is present at
the index -2 and so on until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to access the elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
As we discussed above, we can get an element by using negative indexing. In the above code, the first print statement
returned the rightmost element of the list. The second print statement returned the sub-list, and so on.
Updating List values
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.
Python also provides append() and insert() methods, which can be used to add values to the list.
Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
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.
ist = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Repetition The repetition operator enables the list elements to L1*2 = [1, 2, 3, 4, 1,
be repeated multiple times. 2, 3, 4]
Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Output
1
2
3
4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as follows.
1. list = ["John", "David", "James", "Jonathan"]
2. for i in list:
3. # The i variable will iterate over the elements of the List and contains each element in each iteration.
4. print(i)
Consider the following example in which, we are taking the elements of the list from the user and printing the list on
the console.
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Example -
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
1 cmp(list1, It compares the elements of This method is not used in the Python 3 and the
list2) both the lists. above versions.
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of
the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the
tuple cannot be changed.
Creating a tuple
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. A tuple can be defined as follows.
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
print(type(T1))
print(type(T2))
print(type(T3))
An empty tuple can be created as follows.
T4 = ()
Creating a tuple with single element is slightly different. We will need to put comma after the element to declare the
tuple.
tup1 = ("welco me")
print(type(tup1))
#Creating a tuple with single element
tup2 = ("welcome",)
print(type(tup2))
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index
value.
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i))
count = count+1
Example - 2
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1
\
Tuple indexing and slicing
The indexing and slicing in the tuple are similar to lists. 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 index [] operator. Python also allows us to use the colon operator
to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of tuple that
raised an IndexError.
tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:])
#element 0 to 3 element
print(tuple[:4])
#element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])
Negative Indexing
The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2
to the second last item and so on.
The elements from left to right are traversed using the negative indexing. Consider the following example:
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])
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)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
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.
Membership It returns true if a particular item exists in the print (2 in T1) prints
tuple otherwise false True.
Iteration The for loop is used to iterate over the tuple for i in T1:
elements. print(i)
Output
1
2
3
4
5
S Function Description
N
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2
tuple2) otherwise false.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.
Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used as a
dictionary.
1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]
S List Tuple
N
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality than a The tuple provides less functionality than the list.
tuple.
5 The list is used in the scenario in which we The tuple is used in the cases where we need to
need to store the simple collections with no store the read-only collections i.e., the value of the
constraints where the value of the items can items cannot be changed. It can be used as the key
be changed. inside the dictionary.
6 The lists are less memory efficient than a The tuples are more memory efficient because of
tuple. its immutability.
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.
Creating a 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.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
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. Consider the following example.
# Creating a set which have immutable elements
set1 = {1,2,3, "welcome", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["welcome",4]}
print(type(set2))
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one mutable
element as a list. While checking the type of set2, it raised an error, which means set can contain only immutable
elements.
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.
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Python provides also the remove() method to remove the item from the set. Consider the following example to
remove the items using remove() method.
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
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. We describe these operations as
follows.
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the items that
are present in both the sets.
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Python also provides the union() method which can also be used to calculate the union of two sets. Consider the
following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection
of the two sets is given as the set of the elements that common in both sets
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Using ^ operator
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
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 depending upon
the items present inside the sets.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
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.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation
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.
o Keys must be a single element
o 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.\
Syntax:
Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {}
is used to create empty dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same
result as given by the indexing.
Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the
dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Example:2
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(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("printing the new data");
print(Employee)
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x)
Example 2
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x])
Example - 3
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} for x in Employee.values():
print(x)
Example 4
#for loop to print the items of the dictionary by using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.items():
print(x)
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key,
then the value which is last assigned is considered as the value of the key.
Consider the following example.
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}
for x,y in Employee.items():
print(x,y)
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but we cannot
use any mutable object like the list as the key in the dictionary.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
S Function Description
N
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.
S Method Description
N
1 dic.clear() It is used to delete all the items of the dictionary.
3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
8 dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary
11 len()
12 popItem()
13 pop()
14 count()
15 index()