UNIT-2 Python Programming
UNIT-2 Python Programming
List: A list is an ordered collection of values of any data type that can be stored
in a single variable.
Example:
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
print(fruits)
Nested List: A nested list in Python is a list that contains other lists as its
elements. This allows you to create multi-dimensional data structures, such as
matrices or tables.
Example:
# Basic nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list)
Traversing a list: we can use for loop to traverse all the element in list in
sequential order.
Example:
fruits = ["apple", "banana", "cherry"]
for i in fruits:
print(fruits[i])
Indexing in List: Indexing in Python lists allows you to access individual
elements by their position.
Example:
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry
List Methods:
1. append(x): Adds an item to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4)
2. insert(i, x): Inserts an item at a given position.
Example:
my_list.insert(1, 'a') # List is now [1, 'a', 2, 3, 4, 5, 6]
3. remove(): this method searches for the given element in the list and
removes the first matching element.]
Example:
my_list.remove('a')
4. extend(): This method used to add contents of list2 to the end of list1
Example:
L1 = [10,20]
my_list.extend(L1)
Print(my_list)
5. pop(): Removes and returns the item at the given position in the list.
Example:
L1 = [10,20,30,40,50]
[Link](2)
print(L1)
6. clear(): Removes all items from the list.
Example:
[Link]()
7. count(): Returns the number of times the specified
element appears in the list.
Example:
my_list = [2,1,6,2,10]
my_list.count(2) # Outputs: 2
8. sort(): Sorts the items of the list in place.
Example:
my_list.sort()
my_list.sort(reverse=True)
9. reverse(): Reverses the elements of the list in place.
Example:
my_list.reverse()
10. index(): The index() method searches for the given element from the start
of the list and returns its index.
Example:
my_list = [1, 2, 3, 2]
my_list.index(2) # Outputs: 1
Dictionaries in python:
Dictionary is a mutable unordered collection of elements in the form of a
key:value pairs that associate keys to values, with the requirement that the key
are unique within a dictionary.
Example:
my_dict = {"name": "Tom", "age": 30, "city": "New York"}
Creating dictionary:
Python offers several ways to create dictionaries.
There are two main ways are:
1. Creating Dictionary by using Curly Braces{}.
2. Creating Dictionary by using dict() function.
4. Iterating using items(): the items() method returns a view object that
display a list of dictionary’s (key,value) tuple pairs. The [Link]()
converts each key-value pair in a dictionary into a tuple.
Example:
Employee = {‘name’: ‘Ram’, ‘age’ : 25, ‘Course’ : ‘BCA’}
Dict_item = [Link]()
print(Dict_item)
Comparing Dictionaries.
We can use the == and != operators to test whether two dictionaries contain
the same items.
Using == Operator: Checks if dictionaries have the same key-value pairs
Example:
dict1 = {'name': 'John', 'age': 30}
dict2 = {'name': 'John', 'age': 30}
print(dict1 == dict2) # True
Using != Operator: Checks if dictionaries are different.
Example:
dict1 = {'name': 'John', 'age': 30}
dict2 = {'name': 'Jane', 'age': 25}
print(dict1 != dict2) # True
Built-in functions used on dictionaries:
There are many built in functions for which a dictionary can be passed as an
argument.
• len(): Returns the number of items in the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
print(len(my_dict))
• any(): It returns True if any of the elements in the iterable (in this case,
the dictionary) are true. If the dictionary is empty or all elements are
false, it returns False.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(any(my_dict))
• all(): The all() function returns Boolean true value if all the keys in the
dictionary are true else return false.
Example:
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(all(my_dict))
• Sorted(): The sorted() function is great for sorting dictionaries by keys
or Values.
Example:
my_dict = {'b': 2, 'c': 3, 'a': 1}
sorted_by_keys = dict(sorted(my_dict.items()))
print(sorted_by_keys)
Dictionary Methods: python provides very use full built-in list methods to work
with dictionary.
• clear(): Removes all items from the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
my_dict.clear()
print(my_dict)
• copy(): Returns a shallow copy of the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
my_copy = my_dict.copy()
• get(): Returns the value for a specified key if the key is in the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
value = my_dict.get('name')
• items(): Returns a view object that displays a list of a dictionary's key-
value tuple pairs.
Example:
my_dict = {'name': 'John', 'age': 30}
items = my_dict.items()
print(items)
• keys(): Returns a view object that displays a list of all the keys in the
dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
keys = my_dict.keys()
• pop(): Removes and returns the value for a specified key.
Example:
my_dict = {'name': 'John', 'age': 30}
age = my_dict.pop('age')
print(age)
• popitem(): Removes and returns the last key-value pair as a tuple.
Example:
my_dict = {'name': 'John'}
item = my_dict.popitem()
print(item)
• setdefault(): Returns the value of a key if it exists; otherwise, inserts the
key with a specified value.
Example:
my_dict = {'name': 'John', 'age': 30}
age = my_dict.setdefault('age', 25)
print(my_dict)
• update(): Updates the dictionary with elements from another dictionary
or an iterable of key-value pairs.
Example:
my_dict = {'name': 'John', 'age': 30, ‘city’:‘Bangalore’}
my_dict.update({'city': 'New York', 'age': 31})
print(my_dict)
• values(): Returns a view object that displays a list of all the values in the
dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
values = my_dict.values()
The del statement: The Del keyword is used to delete objects. In python,
everything is an object, so the del keyword can also be used to delete all the
key value pairs in dictionary or a specific item in dictionary.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
del my_dict['age']
print(my_dict)
Tuple in python:
Tuple is a one of the built in data type in python. A tuple is a sequence or
ordered collection of elements of different data types.
Tuple are immutable, tuple allows duplicate values.
Example: my_tuple = (1, 2, 3)
Creating Tuples:
Creating empty tuple
Example:
A = ()
print(A)
Creating Mixed Data type tuple:
Example:
A = (‘Anu’, ‘F’, 21, 92.36)
print(A)
Creating Nested Tuple:
Example:
A = (74, 92,45, (35,85), 56,27)
print(A)
Creating tuple using Tuple() function:
Example:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Outputs: (1, 2, 3)
Tuples are Immutable:
Tuples in Python are immutable, meaning once they are created,
their elements cannot be changed, added, or removed.
Example:
my_tuple = (1, 2, 3)
This will raise an error:
my_tuple[0] = 4 # TypeError: 'tuple' object does not support item assignment
Indexing in tuple:
Each individual element in a tuple can be accessed using a technique called
indexing.
Example: positive indexing in tuple.
my_tuple = (10, 20, 30, 40)
print(my_tuple[0]) # Outputs: 10
print(my_tuple[2]) # Outputs: 30
Step Indexing:
• Allows skipping elements.
Example:
print(my_tuple[::2])
print(my_tuple[::-1])
Slicing in Tuple:
Slicing in tuples allows you to access a specific subset of elements from a tuple.
Example: Positive Slicing in tuple.
my_tuple = (10, 20, 30, 40, 50)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple) # Outputs: (20, 30, 40)
Example: Negative Slicing in tuple.
print(my_tuple[-4:-1]) # Outputs: (20, 30, 40)
Example: Positive and negative Slicing in tuple with Step count
print(my_tuple[::2]) # Outputs: (10, 30, 50)
print(my_tuple[::-1]) # Outputs: (50, 40, 30, 20, 10)
Basic Tuple Operations:
Python allows certain operations on tuple data type such as concatenation,
repetition, membership and comparing.
• Concatenation: Concatenating two tuples means joining two tuples.
Example:
my_tuple = (1,2,3,4)
combined_tuple = my_tuple + (6, 7, 8)
print(combined_tuple) # Outputs: (1, 2, 3, 4, 5, 6, 7, 8)
• Repetition: Python allows us to repeat or replicate the elements of the
tuple using repetition operator which is denoted by symbol *.
Example:
my_tuple = (1,2,3,4)
repeated_tuple = my_tuple * 2
print(repeated_tuple)
• Membership operators (in and not in):
The in operator is a type of membership operator. It is used to check if a
particular element is present in the tuple or not.
The not in operator is a type of membership operator. It is used to check if a
particular element is not present in the tuple.
Example:
print(3 in my_tuple) # Outputs: True
print(6 not in my_tuple) # Outputs: True
• Comparing tuple:
A comparison operator in python, also called python relation operator(<, >, <=,
>=, ==, !=) that compare the values of two operands and returns true or false
based on whether the condition is met.
Example:
A = (10,20,30,40,50)
B = (60,70,80,90,100)
Print(A==B)
Print(A!=B)
Print(A>B)
Print(A<B)
Print(A<=B)
Print(A>=B)
• Copying Tuple: The simplest way to make a copy of the tuple is to assign
a tuple using an assignment operator(=).
Example:
original_tuple = (1, 2, 3)
copied_tuple = original_tuple
print(copied_tuple) # Outputs: (1, 2, 3)
Nested tuple: Nested tuples are tuples within tuples.
They allow you to create complex data structures by nesting one tuple inside
another.
Example:
nested_tuple = (1, (2, 3), (4, (5, 6)))
print(nested_tuple)
Accessing element of nested tuple in index:
Accessing the outer elements:
Example:
print(nested_tuple[0]) # Outputs: 1
print(nested_tuple[1]) # Outputs: (2, 3)
Accessing the inner elements:
Example:
print(nested_tuple[1][0]) # Outputs: 2
print(nested_tuple[2][1][1]) # Outputs: 6
Using Zip() function in tuple: The Zip() method in python takes one or more
iterables (list, sets, string, etc) as arguments and merges each of them element
wise to create a single iterable.
Example:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped = zip(tuple1, tuple2)
print(list(zipped)) # Outputs: [(1, 'a'), (2, 'b'), (3, 'c')]
Unzipping in tuple: There is no special function to unzip zipped iterables, we
can use the zip() method with the * operator to unzip a zip object.
Example:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers) # Outputs: (1, 2, 3)
print(letters) # Outputs: ('a', 'b', 'c')
The del statement: The del keyword is used to delete objects. In python,
everything is an object, so the del keyword can also be used to delete all the
elements in a tuple.
Example:
my_tuple = (1, 2, 3, 4)
del my_tuple
# Now, my_tuple is undefined and trying to access it will raise an error
Example for Creating a New Tuple without an Element
my_tuple = (1, 2, 3, 4)
new_tuple = my_tuple[:1] + my_tuple[2:]
print(new_tuple) # Outputs: (1, 3, 4)
Tuple Dictionary
Tuples are immutable i.e, we can not Dictionaries are mutable and keys
make changes. do not allow duplicates.
Tuple can be created using tuple() Dictionary can be created using the
function. dict() function.
Example : {'companyname':
Example: ('Tutorialspoint', 'simple’,
'Tutorialspoint', 'tagline':
‘easy learning’)
'simplyeasylearning'}
Set in python:
A set in python is a unordered collection of unique elements. A Set is iterable,
mutable and doesn’t allow any type of duplicates as all the elements in set are
unique. Set is used to store multiple elements in a single variable.
Example: S1 = {2,4,6,8}
Creating Set: to create a set, place all elements or items separated by a comma
inside curly braces {}. The bulit-in set() function can also to create a set in
python.
Syntax: Set_name = {value 1,value 2,value 3………value n}
Syntax: Set_name = set()
Syntax: Set_name = set(sequence)
Example:
Intset = {2, 4, 6, 10}
Example:
Emptyset = set()
Example:
S1 = “Python”
Set1 = set(S1)
Traversing a Set: A set is iterable. This means that we can use a for loop to
traverse all the elements in the set.
Example:
S = {10, 20, 30, 40, 50}
For I in S:
Print(I)
Iterating Over two sets simultaneously using zip():
S1 = {10, 20, 30, 40, 50}
S2 = {60, 70, 80, 90, 100}
for (i1, i2) in zip(S1,S2):
Print(i1, i2)
Membership operator (in and not in):
The in operator is a type of membership operator. It is used to check if a
particular element is present in the set or not.
Example:
S1 = {10, 20, 30, 40, 50}
print( 10 in S1)
The not in operator is also a type of membership operator. It is used to check if
a particular element is not present in the set.
Example:
S1 = {10, 20, 30, 40, 50}
print(20 not in S1)
print(60 not in S1)
Comparing Sets: A comparison operator in python also called python relational
operator (<, >, ==,!=, >=, <=).
Equality (==): Check if two sets have the same elements.
Example:
set1 = {1, 2, 3}
set2 = {3, 2, 1}
print(set1 == set2) # Outputs: True
Inequality (!=): Check if two sets do not have the same elements.
Example:
set1 = {1, 2, 3}
set2 = {3, 2, 1}
print(set1 != set2) # Outputs: False
Subset (<= or <): Check if all elements of one set are in another.
Example:
set1 = {1, 2, 3}
subset = {1, 2}
print(subset <= set1) # Outputs: True (subset is a subset of set1)
print(subset < set1) # Outputs: True (subset is a proper subset of set1)
Superset (>= or >): Check if all elements of another set are in the first set.
Example:
superset = {1, 2, 3, 4}
print(superset >= set1) # Outputs: True (superset is a superset of set1)
print(superset > set1) # Outputs: True (superset is a proper superset of set1)
Built In functions used in Set:
len(): Returns the number of elements in the set.
Example:
my_set = {1, 2, 3, 4}
print(len(my_set)) # Outputs: 4
max(): Returns the maximum element in the set.
Example:
my_set = {1, 2, 3, 4}
print(max(my_set)) # Outputs: 4
min(): Returns the minimum element in the set.
Example:
my_set = {1, 2, 3, 4}
print(min(my_set)) # Outputs: 1
sum(): Returns the sum of all elements in the set.
Example:
my_set = {1, 2, 3, 4}
print(sum(my_set)) # Outputs: 10
sorted(): Returns a sorted list of the set's elements.
Example:
my_set = {1, 2, 3, 4}
print(sorted(my_set)) # Outputs: [1, 2, 3, 4]
all(): Returns True if all elements in the set are true.
Example:
my_set = {1, 2, 3}
print(all(my_set)) # Outputs: True
any(): Returns True if any element in the set is true.
Example:
my_set = {0, 2, 3}
print(any(my_set)) # Outputs: True
Set Methods: Python provides very useful built in list method to work with
sets. dir(set) is used to provide list all set methods in python.
• add(element): Adds an element to the set.
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Outputs: {1, 2, 3, 4}
• update(iterable): Adds multiple elements to the set from another iterable.
Example:
my_set = {1, 2, 3, 4}
my_set.update([5, 6])
print(my_set) # Outputs: {1, 2, 3, 4, 5, 6}
• remove(element): Removes an element from the set. Raises a KeyError if
the element is not found.
Example:
my_set = {1, 2, 3, 4, 5, 6}
my_set.remove(3)
print(my_set) # Outputs: {1, 2, 4, 5, 6}
• discard(element): Removes an element from the set if it is present. Does no
thing if the element is not found.
Example:
my_set = {1, 2, 4, 5, 6}
my_set.discard(2)
print(my_set) # Outputs: {1, 4, 5, 6}
• pop(): pop method removes and returns a random element from the
set. Raises a KeyError if the set is empty.
Example:
my_set = {1, 4, 5, 6}
element = my_set.pop()
print(element)
• clear(): Removes all elements from the set.
Example:
my_set = {1, 4, 5, 6}
my_set.clear()
print(my_set) # Outputs: set()
• union(other_set): Returns a new set with all elements from both sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2)
print(union_set) # Outputs: {1, 2, 3, 4, 5}
• intersection(other_set): Returns a new set with elements common to
both sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = [Link](set2)
print(intersection_set) # Outputs: {3}
• difference(): Returns a new set with elements in the first set but not in the
second.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = [Link](set2)
print(difference_set)
• symmetric_difference(other_set): The symmetric_difference() method
return all the items present in given sets, except the items in their insertion.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Outputs: {1, 2, 4, 5}
• issubset(other_set): Checks if the set is a subset of another set.
Example:
set1 = {1, 2, 3}
myset = {1, 2}
print([Link](set1)) # Outputs: True
• isdisjoint(other_set): Checks if the set has no elements in common with
another set.
myset= {6, 7}
print([Link](myset)) # Outputs: True