Python Programming- UNIT 1
Python Programming- UNIT 1
UNIT- II
List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type it means we can modify its element after it is created. 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 [].
A single list may contain DataTypes like Integers, Strings, as well as Objects. A list can
contain any kind of data, i.e., it’s not mandatory to form a list of only one data type. The list
can contain any kind of data in it.
A list can be defined as below
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1and L2 using type() function then it will come out to be a list
as follows:
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
The list has the following characteristics:
o The lists are ordered.
o The element of the list can be accessed by index.
o The lists are the mutable type.
o A list can store various number of elements.
Example 1: Creating a list in Python
# Creating a List
List = []
print("Blank List: ")
print(List)
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List indexing
Elements stored in the lists are associated with a unique integer number known as an index.
The first element is indexed as 0, and the second is 1, and so on. So, a list containing six
elements will have an index from 0 to 5. For accessing the elements in the List, the index is
mentioned within the index operator ([ ]) preceded by the list's name.
Another way we can access elements/values from the list in python is using a negative index.
The negative index starts at -1 for the last element, -2 for the last second element, and so on.
My_List = [3, 4, 6, 10, 8]
OUTPUT:
We also have nested Lists in python. For nested Lists, we first access the index at which the
inner list is stored/indexed in the outer list using the index operator. Then we access the
element from the inner list using the index operator again. It is known as nested indexing. It
is like we access elements in a 2-dimensional array. Unlike in this, we have many elements in
the inner list, but arrays only have a single value at that index.
# Nested List
nested_List = [[6, 2, 8], [1, 3.5, "Interviewbit"],
"preparation"]
print(nested_List[0][1])
print(nested_List[1][2])
OUTPUT:
2
Interviewbit
OUTPUT:
[3, 4, 6, 10, 8, 5]
[3, 4, 6, 7, 8, 5]
[3, 4, 6, 7, 8, 15]
Concatenation: One list may be concatenated with itself or another list using ‘+’ operator.
List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
concat_List = List1 + List2
print(concat_List)
OUTPUT:
[1, 2, 3, 4, 5, 6, 7, 8]
Repeating the elements of the list: We can use the ‘*’ operator to repeat the list elements as
many times as we want.
my_List = [1, 2, 3, 4]
print(my_List*2)
OUTPUT:
[1, 2, 3, 4, 1, 2, 3, 4]
my_List = [1, 2, 3, 4, 5, 6]
print(3 in my_List)
print(10 in my_List)
print(10 not in my_List)
OUTPUT:
True
False
True
Iterating through the list: We can iterate through each item within the list by employing a
for a loop.
my_List = [1, 2, 3, 4, 5]
for n in my_List:
print(n)
OUTPUT:
1
2
3
4
5
Finding the length of List in python: len() method is used to get the length of the list.
my_List = [1, 2, 3, 4, 5]
print(len(my_List))
OUTPUT:
In Python, we can access the elements stored in a range of indexes using the slicing operator
(:). The index put on the left side of the slicing operator is inclusive, and that mentioned on
the right side is excluded.
Slice itself means part of something. So when we want to access elements stored at some part
or range in a list we use slicing.
my_List = ['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
# Accessing elements from index beginning to 5th index
print(my_List[:6])
# Accessing elements from index 3 to 6
print(my_List[3:7])
# Accessing elements from index 5 to end
print(my_List[5:])
# Accessing elements from beginning to end
print(my_List[:])
# Accessing elements from beginning to 4th index
print(my_List[:-6])
OUTPUT:
print(currencies)
Output:
['Dollar', 'Euro', 'Pound', 'Yen']
# create a list
prime_numbers = [2, 3, 5]
Output:
List after extend(): [1, 4, 2, 3, 5]
print('List:', vowel)
Output:
List: ['a', 'e', 'i', 'o', 'u']
4. remove() - Remove the primary item from the list with the required value.
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]
Output:
Updated List: [2, 3, 5, 7, 11]
pop()
5. Remove the item from the required index within the list, and return it.
-
Output:
Removed Element: 5
Updated List: [2, 3, 7]
Output:
List after clear(): []
Returns the index of the specified element in the list. Raises ValueError if an item isn’t
7. index() -
found within the list.
print(index)
Output: 1
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
Output:
Count of 2: 3
Sorts the objects of the list in ascending or descending order. It uses a compare function if
9. sort() -
passed as an argument.
prime_numbers = [11, 3, 7, 5, 2]
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# print vowels
print('Sorted list (in Descending):', vowels)
Output:
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
Output:
Reversed List: [7, 5, 3, 2]
11. copy()- Return a shallow copy of the list i.e. two lists share the identical elements via reference.
# mixed list
prime_numbers = [2, 3, 5]
# copying a list
numbers = prime_numbers.copy()
Output:
Copied List: [2, 3, 5]
Built-in List Methods/Functions in Python
Functions are a group of instructions that typically operate on sequences or objects in python.
Python provides plenty of built-in functions for lists.
1. len()- Calculates and returns the length or size of the list
print(length)
Output: 3
2. max()- Returns the item with maximum value within the list
print(max_number)
Output: 34
3. min()- Returns the item with minimum value within the list
print(min_number)
Output: -4
text = 'Python'
print(text_list)
Output:
['P', 'y', 't', 'h', 'o', 'n']
<class 'list'>
5 Test each element of the list as true or not on the function passed as an
filter(function,sequence)-
. argument there to and returns a filtered iterator.
return False
# Extract elements from the numbers list for which check_even() returns
True
even_numbers_iterator = filter(check_even, numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)
# converting to list
squared_numbers = list(squared_numbers_iterator)
print(squared_numbers)
Output: [4, 16, 36, 64, 100]
7. all()- Returns True if all the items/elements present within the list are true or if the list is empty.
boolean_list = ['True', 'True', 'True']
print(result)
Output: True
sorts the elements of a given iterable in a specific order (ascending or descending) and
8. sorted()-
returns it as a list.
sorted_numbers = sorted(numbers)
print(sorted_numbers)
9. reversed()- computes the reverse of a given sequence object and returns it in the form of a list.
seq_string = 'Python'
# reverse of a string
print(list(reversed(seq_string)))
10. sum()- Returns the sum of all the elements present within the list.
print(total_marks)
Output: 339
Tuple
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets. A tuple can have any
number of items and they may be of different types (integer, float, list, string, etc.).
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5);
A tuple can also be created without using parentheses. This is known as tuple packing.
Output
(3, 4.6, 'dog')
print(my_tuple[0])
print(my_tuple[5])
Output
p
t
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
print(my_tuple[-1])
print(my_tuple[-6])
Output:
t
p
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon [:]
Output: 3
2. count() - This function will help us to find the number of times an element is present in
the tuple.
Example:
tup = (22, 45, 23, 78, 22, 22, 6.89)
tup.count(22)
Output: 3
3. index() - The tuple index() method helps us to find the index or occurrence of an
element in a tuple. This function basically performs two functions:
Giving the first occurrence of an element in the tuple.
Raising an exception if the element mentioned is not found in the tuple.
Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
print(tup.index(45))
print(tup.index(890))
Output:
2
7
4. sorted() - This method takes a tuple as an input and returns a sorted list as an output.
Moreover, it does not make any changes to the original tuple.
Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
sorted(tup)
Output:
[1, 2, 2.4, 3, 4, 22, 45, 56, 890]
5. min() - gives the smallest element in the tuple as an output. Hence, the name is min().
Example:
s = (85, 55, 47, 98, 32, 65, 62, 54)
x = min(s)
print(x)
Output:
32
6. max() - gives the largest element in the tuple as an output. Hence, the name is max().
Example:
tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
max(tup)
Output
890
7. sum() - gives the sum of the elements present in the tuple as an output.
Example:
tup = (22, 3, 45, 4, 2, 56, 890, 1)
sum(tup)
Output:
1023
Tuple Operations
Operator Example
The + operator returns a tuple containing all the elements of the t1= (1,2,3)
first and the second tuple object.
t2= (4,5,6)
t1+t2
Output:
(1, 2, 3, 4, 5, 6)
Operator Example
The * operator Concatenates multiple copies of the same tuple. t1= (1,2,3)
t1*4
Output:
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
Dictionary
The dictionary is an unordered collection that contains key:value pairs separated by commas
inside curly brackets {}.
Dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key:value. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
dict={'Name':'Ravi',"Age":'32'}
Output:
Jack
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output:
Output:
The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha': 21}
The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}
2. clear() method:
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
squares.clear()
print(squares)
Output: {}
Dictionary built in functions
1. len()- Return the length (the number of items) in the dictionary.
Output: 6
Dictionary Methods
1. clear()- The clear() method removes all items from the dictionary.
# dictionary
numbers = {1: "one", 2: "two"}
Output: {}
2. copy()- They copy() method returns a copy (shallow copy) of the dictionary.
copied_marks = original_marks.copy()
print('Original Marks:', original_marks)
print('Copied Marks:', copied_marks)
3. fromkeys()- The fromkeys() method creates a dictionary from the given sequence of
keys and values.
4. get()- The get() method returns the value for the specified key if the key is in the
dictionary.
print(marks.get('Physics'))
Output: 67
5. items()- The items() method returns a view object that displays a list of dictionary's
(key, value) tuple pairs.
print(marks.items())
6. keys()- The keys() method extracts the keys of the dictionary and returns the list of
keys as a view object.
7. pop()- The pop() method removes and returns an element from a dictionary having the
given key.
# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }
element = marks.pop('Chemistry')
print('Popped Marks:', element)
Output:
Popped Marks: 72
8. update()- The update() method updates the dictionary with the elements from another
dictionary object or from an iterable of key/value pairs.
marks.update(internal_marks)
print(marks)
Output:
{'Physics': 67, 'Maths': 87, 'Practical': 48}
Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.
You can execute different blocks of codes depending on the outcome of a condition.
Condition statements always evaluate to either True or False.
If statement
In control statements, the if statement is the simplest form. It takes a condition and evaluates
to either True or False.
If the condition is True, then the True block of code will be executed, and if the condition is
False, then the block of code is skipped, and the controller moves to the next line
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36
Next lines of code
If – else statement
The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.
If the condition is True, then statement 1 will be executed If the condition is False, statement
2 will be executed.
Example
if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")
Output 1:
Correct password
Output 2:
Incorrect Password
If-elif-else statement
In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions
one after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple
conditions one by one and if the condition fulfills, then executes that code.
Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
Output:
Admin
Editor
Guest
Wrong entry
Output 1:
56 is greater than 15
Output 2:
29 is smaller than 78
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the
condition is True. We also call it a loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
1. for loop
2. while loop
For loop in Python
Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.
Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
loop body
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
Output:
The sum is 48
Example:
Output:
6
7
num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print("Sum of first 10 number is:", sum)
Output
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain
manner. For this purpose, we use three types of transfer statements.
1. break statement
2. continue statement
3. pass statements
Break Statement
The break statement is used inside the loop to exit out of the loop. It is useful when we want
to terminate the loop as soon as the condition is fulfilled instead of doing the remaining
iterations. It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately
Example of using a break statement
Output
stop processing.
Continue statement
The continue statement is used to skip the current iteration and continue with the next
iteration.
Example of a continue statement
Output
6
7
Pass statement
A pass statement is a Python null statement. When the interpreter finds a pass statement in
the program, it returns no operation. Nothing happens when the pass statement is executed.
It is useful in a situation where we are implementing new methods or also in exception
handling. It plays a role like a placeholder.
Example
Output