PYTHON PROGRAMMING
Unit 3: Python complex Data types
Today’s Target Lecture -1
Creating lists
Accessing elements in list
By PRAGYA RAJVANSHI
Insert element in list using append(),
insert(),extend() B.Tech, M.Tech( C.S.E)
AKTU PYQs
list
The list is a sequence data type which is used to store the collection of data..
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[ ]. .
list doesn’t need a built-in function for its creation of a list. .
the list may contain mutable elements.
Creating a list with multiple distinct or duplicate elements
A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.
Creating a list with multiple distinct or duplicate elements
Accessing elements from the List
In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. The index must be an integer. Nested lists are accessed using nested indexing. .
Accessing elements from a multi-dimensional list
indexing
Indexing means referring to an element of an inerrable by its position within the iterrable
Negative indexing
In Python, negative sequence indexes represent positions from the end of the array.
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc
Getting the size of Python list
Python len() is used to get the length of the list..
Adding Elements to a Python List
Method 1: Using append() method
Elements can be added to the List by using the built-in append() function. Only one element at a
time can be added to the list by using the append() method, for the addition of multiple elements
with the append() method, loops are used. Tuples can also be added to the list with the use of the
append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing
list with the use of the append() method.
Adding Elements to a Python List(append())
Syntax: list.append(item)
Parameters:
item: an item to be added at the end of the list, The parameter is mandatory and omitting it can give an
error.
Returns: The method doesn’t return any value
Adding Elements to a Python List append()
Adding Elements to a Python List append()
Adding Elements to a Python List append()
Method 2: Using insert() method
append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired
position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two
arguments(position, value).
Method 2: Using insert() method
Method 2: Using insert() method
the syntax of the insert() method is
list.insert(index, element)
Here, element is inserted to the list at the indexth index. All the elements after elem are shifted to the right.).
insert() Parameters
The insert() method takes two parameters:
index - the index where the element needs to be inserted
element - this is the element to be inserted in the list
Method 3: Using extend() method
Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method
is used to add multiple elements at the same time at the end of the list
Method 3: Using extend() method
Syntax: list.extend(iterable)
Parameters:
iterable: Any iterable (list, set, tuple, etc.)
Returns: None
Method 3: Using extend() method
difference between-
basis for Comparison Append() Extend()
To add additional elements or an iterable
To add a single entry to the end of a list, use the
Purpose to the end of a list, use the extend()
append() function.
function.
accepts as input an iterable (such as a list
Input accepts only one input element.
or tuple).
extend() adds each item to the list
The append() function adds the full input to the list
Operation independently after iterating through
as a single item.
each one in the input.
When adding elements from numerous
Since append() only executes one operation, it is
Efficiency iterables or with huge inputs, extend()
typically quicker and more effective than extend().
could take longer.
PYTHON PROGRAMMING
Unit 3: Python complex Data types
Today’s Target Lecture -2
Lists
AKTU PYQs
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
Reverse a list
Python List reverse() is an inbuilt method in the Python programming language that reverses objects of
the List in place i.e. it doesn’t use any extra space but it just modifies the original list.
Syntax: list_name.reverse()
Parameters: There are no parameters.
Returns: The reverse() method does not return any value but reverses the given object from the list.
Reverse a list
Error in reverse() Method
When anything other than list is used in place of list, then it returns an AttributeError.
Error in reverse() Method
When anything other than list is used in place of list, then it returns an AttributeError.
Reverse a List using the Slicing Operator
In this example, the [::-1] slicing operator creates a new list which is the reverse of the my_list
Reversing a sublist using Slicing
In this example, we are reversing a sublist from index 1 to 3 using [::-1] operator.
Accessing Elements in Reversed Order
Reversing a list of mixed DataTypes
Python List Slicing
In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient
problems. Consider a Python list, in order to access a range of elements in a list, you need to slice a list. One
way to do this is to use the simple slicing operator i.e. colon(:). With this operator, one can specify where to
start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.
Python List Slicing Syntax
The format for list slicing is of Python List Slicing is as follows:
Lst[ Initial : End : IndexJump ]
If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step
size IndexJump.
Python List Slicing
Indexing in Python List
Indexing is a technique for accessing the elements of a Python List. There are various ways by which we can
access an element of a list.
Positive Indexes
In the case of Positive Indexing, the first element of the list has the index number 0, and the last element of the list has the
index number N-1, where N is the total number of elements in the list (size of the list).
Python List Slicing
Python List Slicing
Negative Indexes
The below diagram illustrates a list along with its negative indexes. Index -1 represents the last element and -N
represents the first element of the list, where N is the length of the list.
Python List Slicing
Slicing
Slicing
Slicing
Slicing
Slicing
Slicing
Reversed list can be
generated by using a negative
integer as the IndexJump
argument. Leaving the Initial
and End as blank. We need to
choose the Initial and End
values according to a
reversed list if the IndexJump
value is negative
Slicing
Slicing
Slicing
Slicing
List slicing can be used to modify lists or even delete elements from a list.
Slicing
Slicing
By concatenating sliced lists, a new list can be created or even a pre-existing list can
be modified
Slicing
How elements are deleted from list( remove())
Definition and Use of Python list remove() Function
The list remove() function in Python removes the first occurrence of a given item from the list. Here, we
will see how we can remove elements from the Python list by remove function.
It only takes one argument that is the element you want to remove and if that element is not present in
the list, it gives ValueError.
It is very useful in removing incorrect values from a list, without affecting the rest of the list.
How elements are deleted from list( remove())
Remove an element from the list in Python
Deleting Element that doesn’t Exist
Remove all Occurrences of a value from a List
Remove Duplicates from List in Python
Given a list, remove all the 2’s from the list using in keyword
Removing a nested list element from a list
Removing an Element by Value from a List
Python List pop() Method
Python list pop() function removes elements at a specific index.
Python List pop() Method
Definition of Python List pop method()
pop() function removes and returns the value at a specific index. It is an inbuilt function of Python.
It can be used with and without parameters; without a parameter list pop() returns and removes the last
value from the list by default, but when given an index value as a parameter, it only returns and removes the
element at that index.
.
Python List pop() Method
Exception: pop() method raises IndexError when the index is out of range.
Return: Returns The last value or the given index value from the list.
Python List pop method Syntax ()
list_name.pop(index)
Parameters:
index (optional) – The value at index is popped out and removed. If the index is not given, then the last
element is popped out and removed.
.
1. Remove item at last index from list
.
2. Remove Item at specific index from List
.
3. Index Error: pop index out of range
.
4.Remove Item at Negative index from Python List
.
Remove Item from List using Del()
We can Remove Elements from List using Del(). The Python del statement is not a function of List. Items of the list
can be deleted using the del statement by specifying the index of the item (element) to be deleted.
.
PYTHON PROGRAMMING
MODULE 3:conditional and loops
Today’s Target Lecture -3
List operation
List comprehension
By PRAGYA RAJVANSHI
Tuples and operations
B.Tech, M.Tech( C.S.E)
AKTU PYQs
clear()
Python List clear() method removes all items from the List.
Clearing 2D list using list clear() Method
we are creating a 2D list, and we are clearing the list at all indexes of the 2d list and printing it.
Python List count() method
Python List count() method returns the count of how many times a given object occurs in a list using Python.
Python List count() method
List count() method Syntax
syntax: list_name.count(object)
Parameters:
object: is the item whose count is to be returned.
Returns: Returns the count of how many times object occurs in the list.
Exception:
TypeError: Raises TypeError If more than 1 parameter is passed in count() method.
Python List count() method
Exceptions While Using Python list count() method
List count() in Python raises TypeError when more than 1 parameter is passed.
sort()
python list sort() method sorts the elements of a list. In this article, we will see how to sort a list in
Python using sort() function.
Python List sort() Method Syntax
List_name.sort(reverse=True/False, key=myFunc)
Parameters:
reverse (Optional): for reverse=True, it will sort the list descending. Default is reverse=False
key (Optional) – A function to specify the sorting criteria(s).
sort()
Sort a List of Numbers in Ascending Order
Sort a List of Numbers in Ascending Order
Sort a List in Python in Descending Order
Here, we are sorting the list of numbers in Descending order, the same will be for alphabets(Z-A, z-a). To do this
we need to pass reverse=True, this will sort numbers or the alphabet in descending order
Python min() Function
Python min() function returns the smallest of the values or the smallest item in an iterable passed as its
parameter.
Python max() Function
Python max() function returns the largest of the values item in an iterable passed as its parameter.
list of built-in list methods
S.no Method Description
1 append() Used for adding elements to the end of the List.
2 copy() It returns a shallow copy of a list
This method is used for removing all items from the
3 clear()
list.
4 count() These methods count the elements.
5 extend() Adds each element of an iterable to the end of the List
list of built-in list methods
S.no Method Description
6 index() Returns the lowest index where the element appears.
7 insert() Inserts a given element at a given index in a list.
Removes and returns the last value from the List or the given
8 pop()
index value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
list of built-in list methods
S.no Method Description
11 sort() Sort a List in ascending, descending, or user-defined order
12 min() Calculates the minimum of all the elements of the List
13 max() Calculates the maximum of all the elements of the List
LIST COMPREHENSION
List comprehension is used to create a new list from existing sequence.
It is a tool for transforming a given list into another list.
Using list comprehension, we can replace the loop with a single expression that produces the same result
Syntax: newList = [ expression(element) for element in oldList if condition ]
Parameter:
expression: Represents the operation you want to execute on every item within the iterable.
element: The term “variable” refers to each value taken from the iterable.
iterable: specify the sequence of elements you want to iterate through.(e.g., a list, tuple, or string).
condition: (Optional) A filter helps decide whether or not an element should be added to the new list.
Return:The return value of a list comprehension is a new list containing the modified elements that satisfy
the given criteria.
LIST COMPREHENSION
.
WITHOUT LIST COMPREHENSION
Even list using List Comprehension
Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list
in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is
immutable, unlike the Python list which is mutable.
Creating Python Tuples
There are various ways by which you can create a tuple in Python. They are as follows:
Using round brackets
With one item
Tuple Constructor
Create Tuples using Round Brackets ()
Create a Tuple With One Item
Tuple Constructor in Python
What is Immutable in Tuples?
Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and allow
duplicate values. Some Characteristics of Tuples in Python.
We can find items in a tuple since finding any item does not make changes in the tuple.
One cannot add items to a tuple once it is created.
Tuples cannot be appended or extended.
We cannot remove items from a tuple once it is created.
What is Immutable in Tuples?
What is Immutable in Tuples?
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
Using a positive index
Using a negative index
Python Access Tuple using a Positive Index
Access Tuple using Negative Index
tuples with different datatype and without parenthesis
Different Operations Related to Tuples
Different Operations Related to Tuples
Below are the different operations related to tuples in Python:
Concatenation
Nesting
Repetition
Slicing
Deleting(not allowed)
Finding the length
Multiple Data Types with tuples
Conversion of lists to tuples
Tuples in a Loop
Concatenation of Python Tuples
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple..
Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.
Deleting a Tuple in Python
In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error
because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del
keyword
Finding the Length of a Python Tuple
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes
Converting a List to a Tuple
Tuples in a Loop
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description