0% found this document useful (0 votes)
6 views

BCA 402 Python Unit 2

This document provides an overview of Python lists and tuples, detailing their creation, operations, and methods. It covers list operations such as accessing, updating, deleting, slicing, and various built-in functions, as well as tuple characteristics and methods. The document serves as a guide for understanding and utilizing these data structures in Python programming.

Uploaded by

varun.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

BCA 402 Python Unit 2

This document provides an overview of Python lists and tuples, detailing their creation, operations, and methods. It covers list operations such as accessing, updating, deleting, slicing, and various built-in functions, as well as tuple characteristics and methods. The document serves as a guide for understanding and utilizing these data structures in Python programming.

Uploaded by

varun.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Python (Unit-II)

BCA-402

Programme: BCA Course: Python Programming


Fundamentals List Operations used in python
List:
1. Accessing
2. Updating
3. Deleting
4. Indexing
5. Slicing

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

languages = ["Python", "Swift", "C++"]


# access item at index 0
print(languages[0]) # Python
# access item at index 2
print(languages[2]) # C++
In the above example, we have created a list named languages.

Fig: List Index

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.

Negative Indexing in Python


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.
Let's see an example,
languages = ["Python", "Swift", "C++"]

# access item at index 0


print(languages[-1]) # C++

# access item at index 2


print(languages[-3]) # Python

Fig : List Negative Index

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)

# 'i' after the 4th index is searched


index = alphabets.index('i', 4) # 6
print('The index of i:', index)

# 'i' between 3rd and 5th index is searched


index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
5. Slicing:
List slicing in python can be understood as the technique for programmers
to solve efficient problems by manipulating the list as per requirements
through list slicing notation. List slicing is considered a common
practice in Python for accessing a range of elements from a list.

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:

Tuple : Tuples are used to store multiple items in a single variable.


Tuple is one of 4 built-in data types in Python used to store collections of
Data. A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.

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')

3. Delete Tuple Elements


Removing individual tuple elements is not possible.
There is, of course, nothing wrong with putting together another tuple with the
undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
For example −
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
This produces the following result. Note an exception raised,
this is because after del tup tuple does not exist any more
4. Inserting element in tuple:
Tuple is immutable, although you can use the + operator to concatenate several
tuples. The old object is still present at this point, and a new object is created.
Example
Following is an example to append the tuple −
s=(2,5,8)
s_append = s + (8, 16, 67)
print(s_append)
print(s)

Output
(2, 5, 8, 8, 16, 67) (2, 5, 8)

Note− Concatenation is only possible with tuples. It can't be concatenated to


other kinds, such lists.
Tuple functions and methods:
1. len() method
This method returns number of elements in a tuple.
Syntax:
len(<tuple>)
<tuple> refers to user defined tuple whose length we want to find.
Example:
>>> T1=(10,20,30,40)
>>> len(T1) 4 #There are 4 element in tuple.

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:

• Dictionaries are used to store data values in key:value pairs.


• A dictionary is a collection which is ordered*,
• changeable and do not allow duplicates.
• As of Python version 3.7, dictionaries are ordered.
• In Python 3.6 and earlier, dictionaries are unordered.
• Dictionaries are written with curly brackets, and have keys and values:

Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Properties of Dictionary:

• Dictionaries are unordered. A dictionary contains key-value pairs but does


not possess an order for the pairs.
• Keys are unique. Dictionary keys must be unique.
• Keys must be immutable. Dictionary keys must be of an immutable type. ...
• Dictionary comprehension.

Basic Operation on Dictionary:

1. Add or change dictionary items.


2. Remove all the items from the dictionary.
3. Returns all the dictionary's keys.
4. Returns all the dictionary's values.
Build In Dictionary Method and Function:

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:
{}

2. Dictionary get() Method


In Python, the get() method is a pre-built dictionary function that enables you to obtain
the value linked to a particular key in a dictionary. It is a secure method to access
dictionary values without causing a KeyError if the key isn’t present.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))
Output:
Ram
None
3. Dictionary items() Method

In Python, the items() method is a built-in dictionary function that


retrieves a view object containing a list of tuples. Each tuple represents a key
value pair from the dictionary. This method is a convenient way to access both
the keys and values of a dictionary simultaneously, and it is highly efficient.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.items())[1][0])
print(list(d.items())[1][1])

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']

5. Dictionary values() Method


The values() method in Python returns a view object containing all dictionary
values, which can be accessed and iterated through efficiently.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.values()))
Output:
['Ram', '19', 'India']
6. Dictionary update() Method

Python’s update() method is a built-in dictionary function that updates the


key-value pairs of a dictionary using elements from another dictionary or an
iterable of key-value pairs. With this method, you can include new data or
merge it with existing dictionary entries.

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

In Python, the pop() method is a pre-existing dictionary method that


removes and retrieves the value linked with a given key from a dictionary. If
the key is not present in the dictionary, you can set an optional default value to
be returned.

Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.pop('Age')
print(d)
Output:
{'Name': 'Ram', 'Country': 'India'}
8. Dictionary popitem() Method

In Python, the popitem() method is a dictionary function that eliminates


and returns a random (key, value) pair from the dictionary. As opposed to the
pop() method which gets rid of a particular key-value pair based on a given
key, popitem() takes out and gives back a pair without requiring a key to be
specified.
Example:
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d.popitem()
print(d)
d.popitem()
print(d)
Output:
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}
Solve these questions related to dictionary:

1. What is a Python Dictionary?


2. How we can access values in a Python dictionary?
3. What happens when we try to access a key that doesn’t exist
in the dictionary?
4. How do we remove an item from a dictionary?
Solve these questions:

1. Write a Python program to interchange first and elements in a


list.
2. Write a Python program to swap two elements in a list.
3. Write a python program to remove empty tuples from a list
4. write a program to reversing a Tuple
THANK YOU !!!

You might also like