Unit 3: List, Tuple, Dictionaries, Sets and
Strings [16]
3.1 Introduction to Lists
- List Slicing, in operator, List
Methods: append, index, insert, sort, remove, reverse, min, max
3.2 List Comprehension
3.3 Two-Dimensional Lists
3.4 Tuples
3.5 Dictionaries
-
Creating dictionary,
retrieving, adding and removing elements
3.6 Sets
-
Creating Set, Adding and
Removing Elements
-
Set Operations: union,
intersection, difference
3.7 Strings
-
String Operations :
Slicing, Testing, Searching, and Manipulating
Practical Works
• Write program to create
list, add elements in list, remove elements from list and display list items.
• Write program to make use
of list slicing concept to display elements of list.
• Write program to elaborate
different list methods.
• Write program to apply
list comprehension.
• Write program to
illustrate two-dimensional list.
• Write program to create
tuple, add elements in tuple, remove elements from tuple and display tuple
items.
• Write program to create
dictionary, add elements in dictionary, remove elements from dictionary and
display dictionary items.
• Write program to create
set, add elements in set, remove elements from set and display set items.
• Write program to perform
set operations.
Write
program to make use of string manipulation methods and also perform different
string operations
Introduction to Lists:
In Python, the sequence of various data types is stored in a list. A list
is a collection of different kinds of values or items. Since Python lists are
mutable, we can change their elements after forming. The comma (,) and the
square brackets [enclose the List's items] serve as separators.
A list, a type of sequence data, is used to store the collection of data.
Tuples and Strings are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays
defined in other languages, such as Array List in Java and Vector in C++. A
list is a collection of items separated by commas and denoted by the symbol [].
List Declaration:
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
List Slicing:
List slicing in Python is a powerful feature
that allows you to extract portions of a list. You can use the syntax
list[start:stop:step] to create a new list from a subset of an existing list.
Here’s a breakdown of how it works:
- list[start:stop]: Extracts elements from the start index up to, but not
including, the stop index.
- list[start:stop:step]: Extracts elements from the start index up to, but not
including, the stop index, stepping by step.
# Define a list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from index 2 to 5
print(my_list[2:5]) # Output: [2, 3, 4]
# Slice from the beginning to index 4
print(my_list[:4]) # Output: [0, 1, 2, 3]
# Slice from index 5 to the end
print(my_list[5:]) # Output: [5, 6, 7, 8, 9]
# Slice with a step of 2
print(my_list[1:8:2]) # Output: [1, 3, 5, 7]
# Slice with a negative step (reverses the
list)
print(my_list[8:1:-1]) # Output: [8, 7, 6, 5, 4, 3, 2]
# Slice with negative indices
print(my_list[-4:-1]) # Output: [6, 7, 8]
In operator:
The in operator in Python is used to check
if an element exists in a list. It returns True if the element is found and
False otherwise.
Syntax:
element in list
Example:
# Define a list
my_list = [10, 20, 30, 40, 50]
# Check if 30 is in the list
print(30 in my_list) # Output: True
# Check if 100 is in the list
print(100 in my_list) # Output: False
# Check if a string is in a list of strings
string_list = ['apple', 'banana', 'cherry']
print('banana' in string_list) # Output: True
print('orange' in string_list) # Output: False
List Methods:
Append():
Adds a single element to the end of the
list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Index():
Returns the index of the first
occurrence of a value. Raises an error if the value is not found.
my_list = [10, 20, 30]
print(my_list.index(20)) # Output: 1
Insert:
Inserts an element at a specific index.
my_list = [1, 2, 3]
my_list.insert(1, 'a')
print(my_list) # Output: [1, 'a', 2, 3]
Sort:
Sorts the elements of the list in place,
either in ascending or descending order.
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
# Sort in descending order
my_list.sort(reverse=True)
print(my_list) # Output: [3, 2, 1]
Remove:
Removes the first occurrence of a value
from the list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
Reverse:
Reverses the order of the elements in
the list in place.
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
min:
The min() function returns the smallest
element in the list.
Syntax:
min(list)
Example:
my_list = [5, 2, 9, 1, 7]
print(min(my_list)) # Output: 1
max:
The max() function returns the largest
element in the list.
Syntax:
max(list)
Example:
my_list = [5, 2, 9, 1, 7]
print(max(my_list)) # Output: 9
3.2 List Comprehension
List comprehension in Python is a concise
way to create lists by embedding a loop and optional condition(s) inside square
brackets. It allows you to generate new lists from existing iterables in a
clear and readable manner.
Syntax:
[expression for item in iterable if
condition]
expression:
The value to be added to the new list.
item:
The current item in the iteration.
iterable:
The collection being iterated over (like a list, range, or string).
condition
(optional): Filters elements based on some condition (optional).
Example : List Comprehension with
Condition
Create a list of even numbers from 1 to 10:
evens = [x for x in range(1, 11) if x % 2 ==
0]
print(evens)
# Output: [2, 4, 6, 8, 10]
3.3 Two-Dimensional Lists
A two-dimensional list (or 2D list)
in Python is a list of lists, where each element is itself a list. You can
visualize it like a table (or matrix) with rows and columns.
Example of a 2D List:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
This represents:
1
2 3
4
5 6
7
8 9
3.4 Tuples
A comma-separated group of items is called
a Python tuple. The ordering, settled items, and reiterations of a tuple are to
some degree like those of a rundown, but in contrast to a rundown, a tuple is unchanging.
The main difference between the two is that
we cannot alter the components of a tuple once they have been assigned. On the
other hand, we can edit the contents of a list.
Example
- ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
- Tuples are an
immutable data type, meaning their elements cannot be changed after they
are generated.
- Each element in a
tuple has a specific order that will never change because tuples are
ordered sequences.
Forming a Tuple:
All the objects-also known as
"elements"-must be separated by a comma, enclosed in parenthesis ().
Although parentheses are not required, they are recommended.
Any number of items, including those with
various data types (dictionary, string, float, list, etc.), can be contained in
a tuple.
Code
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
3.5 Dictionaries
Dictionaries are a useful data structure for
storing data in Python because they are capable of imitating real-world data
arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using
a Python dictionary.
- This data structure is mutable
- The components of dictionary were
made using keys and values.
- Keys must only have one component.
- Values can be of any type,
including integer, list, and tuple.
A dictionary is, in other words, a group of
key-value pairs, where the values can be any Python object. The keys, in
contrast, are immutable Python objects, such as strings, tuples, or numbers.
Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and
before, dictionaries are generally unordered.
Creating the Dictionary
Curly brackets are the simplest way to
generate a Python dictionary, although there are other approaches as well. With
many key-value pairs surrounded in curly brackets and a colon separating each
key from its value, the dictionary can be built. (:). The following provides
the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The
keys Name and Age are the strings which comes under the category
of an immutable object.
Adding Dictionary Values
The dictionary is a mutable data type, and
utilising the right keys allows you to change its values. Dict[key] = value and
the value can both be modified. An existing value can also be updated using the
update() method.
Code
# 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)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky',
'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint',
'Emp_ages': (20, 33, 24)}
removing Elements using del Keyword:
The items of the dictionary can be deleted
by using the del keyword as given below.
Code
Employee = {"Name": "David", "Age": 30,
"salary":55000,"Company":"WIPRO"}
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)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary':
55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
3.6 Sets
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 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 1: Using curly braces
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)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday',
'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: Using set() method
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)
Output:
{'Friday', 'Wednesday', 'Thursday',
'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
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. Consider the following example.
Example: 1 - Using add() method
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)
Output:
printing the original set ...
{'February', 'May', 'April', 'March',
'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April',
'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
To add more than one item in the set, Python
provides the update() method. It accepts iterable as an argument.
Consider the following example.
Example - 2 Using update() function
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);
Output:
printing the original set ...
{'January', 'February', 'April', 'May',
'June', 'March'}
updating the original set ...
printing the modified set ...
{'January', 'February', 'April', 'August',
'October', 'May', 'June', 'July', 'September', 'March'}
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.
Consider the following example.
Example-1 Using discard() method
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)
Output:
printing the original set ...
{'February', 'January', 'March', 'April',
'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June
Python provides also the remove()
method to remove the item from the set. Consider the following example to
remove the items using remove() method.
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.
Union:
Union of two Sets
To combine two or more sets into one set in
Python, use the union() function. All of the distinctive characteristics from
each combined set are present in the final set. As parameters, one or more sets
may be passed to the union() function. The function returns a copy of the set
supplied as the lone parameter if there is just one set. The method returns a
new set containing all the different items from all the arguments if more than
one set is supplied as an argument.
Consider the following example to calculate
the union of two sets.
Example 1: using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Output:
{'Friday', 'Sunday', 'Saturday', 'Tuesday',
'Wednesday', 'Monday', 'Thursday'}
Python also provides the union()
method which can also be used to calculate the union of two sets. Consider the
following example.
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday',
'Wednesday', 'Sunday', 'Saturday'}
Now, we can also make the union of more than
two sets using the union() function, for example:
Program:
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.union(set2, set3)
# Print the common elements
print(common_elements)
Output:
{1, 2, 3, 4, 5}
Intersection:
The intersection of two sets
To discover what is common between two or
more sets in Python, apply the intersection() function. Only the items in all
sets being compared are included in the final set. One or more sets can also be
used as the intersection() function parameters. The function returns a copy of
the set supplied as the lone parameter if there is just one set. The method
returns a new set that only contains the elements in all the compared sets if
multiple sets are supplied as arguments.
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.
Consider the following example.
Example 1: Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
Output:
{1,2,5}
Similarly, as the same as union function, we
can perform the intersection of more than two sets at a time,
For Example:
Program
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.intersection(set2, set3)
# Print the common elements
print(common_elements)
Output:
{3}
Difference:
Difference between the two sets
The difference of two sets can be calculated
by using the subtraction (-) operator or intersection() method. Suppose
there are two sets A and B, and the difference is A-B that denotes the
resulting set will be obtained that element of A, which is not present in the
set B.
Consider the following example.
Example 1 : Using subtraction ( - )
operator
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
3.7 Strings
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.
Consider the following example in Python to
create a string.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str
using a Python script
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.
Creating String in Python
We can create a string by enclosing the
characters in single-quotes or double- quotes. Python also provides
triple-quotes to represent the string, but it is generally used for multiline
string or docstrings.
#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)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
No comments:
Post a Comment