BCA 402 Python Unit 2
BCA 402 Python Unit 2
BCA-402
Creating a list:
We create a list by placing elements inside [], separated by commas.
E.g.:
ages = [19, 26, 23]
print(ages)
# Output: [19, 26, 23]
A list can
❖ store elements of different types (integer, float, string, etc.)
❖ store duplicate elements
# list with elements of different data types list1 = [1, "Hello", 3.4]
# list with duplicate elements list1 = [1, "Hello", 3.4, "Hello", 1]
# empty list list3 = []
1. Accessing List Elements
• In Python, lists are ordered and each item in a list is associated with a
number. The number is known as a list index.
• The index of the first element is 0, second element is 1 and so on. For
example
Here, we can see each list item is associated with the index number. And we
have used the index number to access the items.
Remember: The list index always starts with 0. Hence, the first element of a list
is present at index 0, not 1.
Note: If the specified index does not exist in a list, Python throws
the IndexError exception.
2. Updating List Items:
You can update single or multiple elements of lists by giving the slice
on the left-hand side of the assignment operator.
For e.g.:
a=[“Neelima”,10, “Shifa”,12.5]
a[1]=“Sania”
print(a[1])
Output
Sania
3. Removing List Items :
The del keyword also removes the specified index:
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Output
['banana', 'cherry']
4. Indexing:
Python index() is an inbuilt function in Python, which searches for a
given element from the start of the list and returns the index of the first
occurrence.
Syntax of List index() Method
Syntax: list_name.index(element, start, end)
Parameters:
element – The element whose lowest index will be returned.
start (Optional) – The position from where the search begins.
end (Optional) – The position from where the search ends.
Return: Returns the lowest index where the element appears.
For e.g.:
animals = ['cat', 'dog', 'rabbit', 'horse']
# get the index of 'dog'
index = animals.index('dog')
print(index)
# Output: 1
Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 1
print('The index of e:', index)
Syntax:
Lst[ Initial : End : IndexJump ]
my_list = [2, 7, 9, 44, 15]
print(my_list[:])
Output:
[2, 7, 9, 44, 15]
Explanation: As we have not exactly sliced the list, and used simply : ,' we get
all the elements of the list as shown above.
Get all the Items After a Specific Position
Given below example explains how we can Get all the Items After a
Specific Position from a list.
Code:
my_list = [12, 22, 43, 64, 85]
print(my_list[2:])
Output:
[43, 64, 85]
Explanation:
Above example illustrates , if we want to call all the elements starting from a
specific index, we can do so by mentioning the index before : as shown in
example above. Here we have element at index 2 and all the elements after
index 2 are printed.
It must be noted that indexing starts from 0 therefore, Item on the index 2 shall
also be included.
Get all the Items Before a Specific Position
Given below example explains how we can Get all the Items Before a
Specific Position from a list.
Code:
my_list = [21, 32, 53, 64, 56]
print(my_list[:2])
Output:
[21, 32]
Explanation: The above example shows how we can get all the elements
occurring before a specific index. We use the : colon to specify the last
index after it. As seen above our list got sliced at the 2nd index, and as we
know the index at the end is not included.
Explore free
Get all the Items from One Position to Another Position
Given below example explains how we can Get all the Items from One
Position to Another Position from a list.
Code:
my_list = [21, 42, 32, 47, 95]
print(my_list[2:4])
Output:
[32, 47]
Explanation:
Whenever we want the list to be sliced in manner that the value between two
index can be obtained we use the process as shown in above example. here
we have specified the start and end index to give the point at which the our
output list must start and the point before which our list must stop.
Above gives a new list that have items between 2nd and the 4th positions. The
new list, starting position (i.e. 2) is included and the ending position (i.e. 4) is
excluded.
Some of the most widely used list operations in Python include
the following:
1. append()
The append() method adds elements at the end of the list.
This method can only add a single element at a time.
You can use the append() method inside a loop to add multiple elements .
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
myList.append(4)
myList.append(5)
myList.append(6)
for i in range(7, 9):
myList.append(i)
print(myList)
Output:
[1, 2, 3, 'EduCBA', 'makes learning fun!‘,4,5,6,7,8]
2. extend()
The extend() method adds more than one element at the end of the list.
Although it can add more than one element, unlike append(), it adds them at
the end of the list like append().
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
myList.extend([4, 5, 6])
for i in range(7, 11):
myList.append(i)
print(myList)
Output:
[1, 2, 3, 'EduCBA', 'makes learning fun!‘,4,5,6,7,8,9,10]
3. insert()
The insert() method can add an element at a given position in the list.
Thus, unlike append(), it can add elements at any position, but like append(),
it can add only one element at a time. This method takes two arguments.
The first argument specifies the position, and the second argument specifies the
element to be inserted.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
Output:
myList = [1, 2, 3, 4,5,6,'EduCBA', 'makes learning fun!']
4. remove()
The remove() method removes an element from the list. Only the first occurrence of
the same element is removed in the case of multiple occurrences.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
myList.remove('makes learning fun!')
print(myList)
Output:
[1, 2, 3, 'EduCBA‘]
5. pop()
The method pop() can remove an element from any position in the list.
The parameter supplied to this method is the element index to be removed.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
myList.pop(3)
print(myList)
Output:
[1, 2, 3, 'makes learning fun!']
6. reverse()
You can use the reverse() operation to reverse the elements of a list.
This method modifies the original list. We use the slice operation with
negative indices to reverse a list without modifying the original.
Specifying negative indices iterates the list from the rear end to the
front end of the list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print(myList[::-1])
# does not modify the original list myList.reverse()
# modifies the original list print(myList)
Output:
['makes learning fun!,'EduCBA',3,2,1 ]
7. len()
The len() method returns the length of the list, i.e., the number of elements
in the list.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
print(len(myList))
Output:
5
8. count()
The function count() returns the number of occurrences of a given element in
the list.
Code:
myList = [1, 2, 3, 4, 3, 7, 3, 8, 3]
print(myList.count(3))
Output:
4
9. min() & max()
The min() method returns the minimum value in the list. The max() method
returns the maximum value in the list. Both methods accept only homogeneous
lists, i.e., lists with similar elements.
Code:
myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
Output:
1
10. concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is
performed using the + sign. It’s important to note that the individual lists are not
modified, and a new combined list is returned.
Code:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)
Output:
[1, 2, 3, 'EduCBA', 'makes learning fun!‘,4, 5, 'Python', 'is fun!‘]
Tuples and basic tuple operations:
Example:
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Output:
('apple', 'banana', 'cherry')
1. Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
print "tup1[0];
When the above code is executed, it produces the following result −
tup1[0]: physics
2. Updating Tuples:
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2; print tup3;
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Output
(2, 5, 8, 8, 16, 67) (2, 5, 8)
2. max()
This method returns largest element of a tuple.This method works only if the tuple
contains all values of same type. If tuple contains values of different data types then,
it will give error stating that mixed type comparison is not possible:
Syntax :
max(<tuple>)
<tuple> refers to name of tuple in which we want to find maximum value.
Example :
>>> T1=[10,20,30,40]
>>> max(T1) 40 # 40 is the maximum value in tuple T1.
3. min()
This method returns smallest element of a tuple. This method works only if the
tuple contains all values of same type. If tuple contains values of different data
types then, it will give error stating that mixed type comparison is not possible:
Syntax :
min(<tuple>)
<tuple> refers to name of tuple in which we want to find minimum value.
Example :
>>> T1=[10,20,30,40]
>>> min(T1) 10 #10 is the minimum value.
4. index()
This method is used to find first index position of value in a tuple. It returns error if
value is not found in the tuple.
Syntax:
Tuple.index (<Val>)
<Val> refers to the value whose index we want to find in Tuple.
Example:
>>> T1=[13,18,11,16,18,14]
>>> print(T1.index(18)) 1 #Index of first occurance of 18 is shown i.e. 1.
5. count()
This function is used to count and return number of times a value exists in a tuple.
If the given value is not in the tuple, it returns zero.
Syntax:
Tuple.count(<value>)
<value> refers to the value whose count we want to find.
Example 1:
>>> T1=[13,18,11,16,18,14] >>> T1.count(18) #18 appears twice in tuple T1. 2
6. tuple()
This method is used to create a tuple from different types of values.
Syntax:
Tuple(<sequence>)
<sequence> refers to a sequence type object that we want to convert to a tuple.
Example 1 – Creating empty tuple
>>> t=tuple()
>>> t ()
Example 2 – Creating a tuple from a list
>>>t=tuple([1,2,3])
>>>t (1,2,3)
Dictionary:
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Properties of Dictionary:
1. clear()
Removes all items from the dictionary
2. copy()
Returns a shallow copy of the dictionary
3. fromkeys()
Creates a dictionary from the given sequence
4. get()
Returns the value for the given key
5. items()
Return the list with all dictionary keys with values
6. popitem()
Returns and removes the key-value pair from the dictionary
7. setdefault()
Returns the value of a key if the key is in the dictionary else inserts the key with
a value to the dictionary
8. values()
Updates the dictionary with the elements from another dictionary
9. update()
Returns a list of all the values available in a given dictionary
10. pop()
Returns and removes the element with the given key
11. keys()
Returns a view object that displays a list of all the keys in the dictionary in
order of insertion
1. Dictionary clear() Method
The clear() method in Python is a built-in method that is used to remove all the
elements (key-value pairs) from a dictionary. It essentially empties the dictionary,
leaving it with no key-value pairs.
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)
Output:
{}
Output:
Age
19
4. Dictionary keys() Method
The keys() method in Python returns a view object with dictionary keys,
allowing efficient access and iteration.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.keys()))
Output:
['Name', 'Age', 'Country']
Example:
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}
d1.update(d2)
print(d1)
Output:
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
7. Dictionary pop() Method
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.pop('Age')
print(d)
Output:
{'Name': 'Ram', 'Country': 'India'}
8. Dictionary popitem() Method