Unit Iv Python
Unit Iv Python
UNIT IV
Lists: Using List- List Assignment and Equivalence – List Bounds- Slicing - Lists and
Functions- Prime Generation with a List.List Processing: Sorting-Flexible Sorting- Search-
List Permutations- Randomly Permuting a List- Reversing a List.
LISTS IN PYTHON
A list in Python is used to store the sequence of various types of data. A list can be
defined as a collection of values or items of different types. Python lists are mutable type which
implies that we may modify its element after it has been formed. The items in the list are
separated with the comma (,) and enclosed with the square brackets [].
Although Python has six data types that may hold sequences, the list is the most popular and
dependable form. The collection of data is stored in a list, a sequence data type. Similar sequence
data formats are Tuples and String.
A list is a group of items that are denoted by the symbol [] and subdivided by commas.
List Declaration
Code
1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4. # printing the list
5. print(list1)
6. print(list2)
7. # printing the type of list
8. print(type(list1))
9. print(type(list2))
Output:
UNIT IV Page 1
CCS 62 – PYTHON PROGRAMMING
Characteristics of Lists
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b
Output:
False
The identical elements were included in both lists, but the second list modified the index position
of the fifth element, which is against the lists' intended order. When the two lists are compared,
false is returned.
Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
UNIT IV Page 2
CCS 62 – PYTHON PROGRAMMING
The indexing is processed in the same way as it happens with the strings. The elements of the list
can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
The initial index is represented by the start parameter, the ending index is determined by the
step, and also the number of elements which are "stepped" through is the value of the end
parameter. In the absence of a specific value for step, the default value equals 1. Inside the
resultant SubList, the item also with index start would be present, but the one with the index
finish will not. A list's initial element seems to have the index of 0.
Code
UNIT IV Page 3
CCS 62 – PYTHON PROGRAMMING
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
In contrast to other languages, Python gives you the option to employ negative indexing
as well. From the right, the negative indices are counted. The final element on the right-hand side
of the list is represented by the index -1, followed by the next member on the left at the index -2,
and so on until the last element on the left is reached.
Let's have a look at the following example where we will use negative indexing to access the
elements of the list.
Code
UNIT IV Page 4
CCS 62 – PYTHON PROGRAMMING
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
In Python, lists are mutable objects, which means that you can modify their contents
without creating a new object. You can assign a new value to an element in a list using indexing
or append new elements to the list using the append() method.
Here's an example:
# create a list
my_list = [1, 2, 3]
print(my_list) # Output: [1, 2, 3]
# assign a new value to an element in the list
my_list[1] = 4
print(my_list) # Output: [1, 4, 3]
# append new elements to the list
my_list.append(5)
print(my_list) # Output: [1, 4, 3, 5]
In the above example, we first create a list [1, 2, 3] and assign it to a variable my_list.
Then we change the second element of the list to 4 using list indexing, and append a new
element 5 to the end of the list using the append() method.
UNIT IV Page 5
CCS 62 – PYTHON PROGRAMMING
List Equivalence:
# create two lists
list1 = [1, 2, 3]
list2 = [1, 2, 3]
# test for list equivalence using the equality operator
if list1 == list2:
print("The lists are equivalent")
else:
print("The lists are not equivalent")
In the above example, we create two lists list1 and list2 that have the same elements in
the same order, and test for their equivalence using the equality operator ==. Since the two lists
have the same values in the same order, they are considered equivalent.
In the above example, we create two lists list3 and list4 that have the same elements, but
in a different order. We test for their equivalence using the equality operator ==. Since the two
lists have the same values, but not in the same order, they are not considered equivalent.
UNIT IV Page 6
CCS 62 – PYTHON PROGRAMMING
In Python, a list is a built-in data structure that allows you to store an ordered collection
of items. To work with lists, you may need to know their bounds, which refers to the range of
valid indices for the list.
The bounds of a list in Python start at index 0 and go up to the length of the list minus 1.
For example, if you have a list my_list with length 5, the valid indices are 0, 1, 2, 3, and 4.
You can get the length of a list using the built-in len() function, like this:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Output: 5
To access elements of a list, you can use square brackets with the index of the element
you want to retrieve.
For example:
my_list = [1, 2, 3, 4, 5]
first_item = my_list[0]
third_item = my_list[2]
last_item = my_list[-1] # Negative indices count from the end of the list
It's important to note that trying to access an index outside the bounds of the list will
result in an IndexError. For example, if you try to access my_list[5], which is outside the
bounds of the list, you will get an error:
my_list = [1, 2, 3, 4, 5]
sixth_item = my_list[5] # Raises an IndexError, since there is no index 5 in the list
In Python, you can slice a list to extract a subset of its elements. Slicing a list involves
specifying a start index, an end index (exclusive), and an optional step size. Here are some
examples of how to slice a list in Python:
The below program transforms the above illustration into python code:
UNIT IV Page 7
CCS 62 – PYTHON PROGRAMMING
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[1:5])
Output:
[70, 30, 20, 90]
Below are some examples which depict the use of list slicing in Python:
Example 1:
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Leaving any argument like Initial, End or IndexJump blank will lead to the use of default
values i.e 0 as Initial, length of list as End and 1 as IndexJump.
Example 2:
UNIT IV Page 8
CCS 62 – PYTHON PROGRAMMING
# Initialize list
List = ['Geeks', 4, 'geeks !']
Output:
Original List:
['Geeks', 4, 'geeks !']
Sliced Lists:
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']
Example 3:
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
UNIT IV Page 9
CCS 62 – PYTHON PROGRAMMING
Output:
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[1, 2, 3, 8, 9]
[1, 3, 5, 7, 9, 2, 4, 6, 8]
By concatenating sliced lists, a new list can be created or even a pre-existing list can be
modified.
Python List Methods has multiple methods to work with Python lists, Below we’ve
explained all the methods you can use with Python lists, for example, append(), copy(),
insert() and more.
List Methods
1 append() Used for appending and adding elements to the end of the List.
3 clear() This method is used for removing all items from the list.
UNIT IV Page 10
CCS 62 – PYTHON PROGRAMMING
5 extend() Adds each element of the iterable to the end of the List
8 pop() Removes and returns the last value from the List or the given index value.
Used for appending and adding elements to List. It is used to add elements to the last
position of the List in Python.
Syntax:
list.append (element)
UNIT IV Page 11
CCS 62 – PYTHON PROGRAMMING
List.append(20544)
print(List)
Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]
insert()
Inserts an element at the specified position.
Syntax:
list.insert(<position, element)
Note: Position mentioned should be within the range of List, as in this case between 0 and 4,
elsewise would throw IndexError.
List.insert(2,10087)
print(List)
Output:
['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]
extend()
Adds contents to List2 to the end of List1.
Syntax
List1.extend(List2)
UNIT IV Page 12
CCS 62 – PYTHON PROGRAMMING
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
List1.extend(List2)
print(List1)
List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Other functions of List
sum()
Calculates the sum of all the elements of the List.
Syntax
sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
UNIT IV Page 13
CCS 62 – PYTHON PROGRAMMING
15
What happens if a numeric value is not used a parameter?
The sum is calculated only for Numeric values, elsewise throws TypeError.
See example:
print(sum(List))
Output:
Traceback (most recent call last):
File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
count()
Calculates total occurrence of a given element of List.
Syntax:
List.count(element)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:
4
length
Calculates the total length of the List.
Syntax:
len(list_name)
UNIT IV Page 14
CCS 62 – PYTHON PROGRAMMING
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:
10
index()
Returns the index of the first occurrence. The start and End index are not necessary
parameters.
Syntax:
List.index(element[,start[,end]])
Python
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output:
1
Another example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2,2))
Output:
4
min()
Calculates minimum of all the elements of List.
Syntax:
UNIT IV Page 15
CCS 62 – PYTHON PROGRAMMING
numbers = [5, 2, 8, 1, 9]
print(min(numbers))
Output
1
max()
Calculates maximum of all the elements of List.
Syntax:
max(iterable, *iterables[, key])
numbers = [5, 2, 8, 1, 9]
print(max(numbers))
Output
9
Syntax:
Deletion of List Elements
To Delete one or more elements, i.e. remove an element, many built-in functions can be used,
such as pop() & remove() and keywords such as del.
pop()
The index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs.
UNIT IV Page 16
CCS 62 – PYTHON PROGRAMMING
print(List.pop())
Output:
2.5
print(List.pop(0))
Output:
2.3
del()
Element to be deleted is mentioned using list name and index.
Syntax:
del list.[index]
del List[0]
print(List)
Output:
[4.445, 3, 5.33, 1.054, 2.5]
remove()
Element to be deleted is mentioned using list name and element.
Syntax
list.remove(element)
UNIT IV Page 17
CCS 62 – PYTHON PROGRAMMING
List.remove(3)
print(List)
Output:
[2.3, 4.445, 5.33, 1.054, 2.5]
To generate prime numbers using a list in Python, we can use the following algorithm:
def generate_primes(n):
primes = []
# empty list to hold prime numbers
num = 2
# start with 2,
the first prime number
while len(primes) < n:
is_prime = True
# assume the number is prime until proven otherwise
for prime in primes:
if num % prime == 0:
is_prime = False
break
if is_prime:
primes.append(num)
num += 1
return primes
UNIT IV Page 18
CCS 62 – PYTHON PROGRAMMING
This function takes a parameter n that specifies the number of primes to generate. It uses
a while loop to continue generating primes until the desired number have been found. For each
number, it checks if it is divisible by any of the prime numbers found so far using a for loop. If it
is not divisible, then it is a prime number and should be added to the list. Finally, it increments
the number being checked and repeats the loop until enough prime numbers have been found.
To use this function, we can simply call it with the desired number of primes to generate:
primes = generate_primes(10)
print(primes)
# prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
This will generate a list of the first 10 prime numbers and print it to the console.
List processing in Python refers to the manipulation of lists, which are a type of data
structure that can hold a collection of values. Lists in Python are ordered and mutable, which
means that you can add, remove, and modify elements in a list.
List processing can involve a wide range of operations, such as accessing specific
elements of a list, adding new elements to a list, removing elements from a list, sorting a list, and
more. Python provides a variety of built-in functions and methods that make it easy to perform
these operations on lists.
List processing is a fundamental skill in Python programming, as lists are one of the most
commonly used data structures in the language. Being able to process lists efficiently and
effectively is essential for many programming tasks, such as data analysis, text processing, and
web development.
In Python, you can process lists using a variety of built-in functions and methods. Here are
some common list processing techniques in Python:
1. Accessing list elements: You can access an individual element of a list by its index. For
example, if my_list is a list, you can access the first element using my_list[0].
2. Modifying list elements: You can modify an individual element of a list by assigning a
new value to it. For example, my_list[0] = 42 would change the first element of my_list
to 42.
3. Adding elements to a list: You can add elements to the end of a list using the append()
method. For example, my_list.append(42) would add the value 42 to the end of my_list.
4. Removing elements from a list: You can remove elements from a list using the remove()
method. For example, my_list.remove(42) would remove the first occurrence of the value
42 from my_list.
5. Sorting a list: You can sort a list in ascending order using the sort() method. For example,
my_list.sort() would sort the elements of my_list in ascending order.
UNIT IV Page 19
CCS 62 – PYTHON PROGRAMMING
6. Reversing a list: You can reverse the order of elements in a list using the reverse()
method. For example, my_list.reverse() would reverse the order of elements in my_list.
7. Slicing a list: You can extract a portion of a list using slicing. For example, my_list[2:5]
would extract elements 2 through 4 (inclusive) of my_list.
8. Copying a list: You can create a copy of a list using the copy() method or by slicing the
entire list. For example, my_copy = my_list.copy() or my_copy = my_list[:] would create
a copy of my_list.
Python provides a built-in sorted() function that can be used to sort various types of
objects, including lists, tuples, and even dictionaries. The sorted() function returns a new
sorted list and leaves the original list unchanged.
By default, the sorted() function sorts items in ascending order, but you can also sort in
descending order by specifying the reverse=True argument.
Here are some examples of using the sorted() function for flexible sorting in Python:
Syntax
list.sort(reverse=True|False, key=myFunc)
Example
cars.sort()
Parameter Values
UNIT IV Page 20
CCS 62 – PYTHON PROGRAMMING
Parameter Description
More Examples
Example
cars.sort(reverse=True)
Example
cars.sort(key=myFunc)
UNIT IV Page 21
CCS 62 – PYTHON PROGRAMMING
Example
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
OUTPUT:
Example
cars.sort(reverse=True, key=myFunc)
OUTPUT:
UNIT IV Page 22
CCS 62 – PYTHON PROGRAMMING
Python provides a built-in sorted() function that can be used to sort various types of
objects, including lists, tuples, and even dictionaries. The sorted() function returns a new sorted
list and leaves the original list unchanged.
By default, the sorted() function sorts items in ascending order, but you can also sort in
descending order by specifying the reverse=True argument.
Here are some examples of using the sorted() function for flexible sorting in Python:
my_list = [5, 2, 8, 1, 9]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 5, 8, 9]
In all of these examples, the sorted() function is used to sort a collection of objects in a
flexible way, based on different criteria such as value or position within the object. This makes it
a powerful tool for data processing and analysis in Python.
A list is a common data structure in Python that can store multiple values in a single
variable. To search for an item in a list, there are multiple approaches you can take, depending on
your needs and the structure of your code.
UNIT IV Page 23
CCS 62 – PYTHON PROGRAMMING
UNIT IV Page 24
CCS 62 – PYTHON PROGRAMMING
REVERSING A LIST
UNIT IV Page 25
CCS 62 – PYTHON PROGRAMMING
list.reverse()
reverse() parameter
The reverse() method doesn't return any value. It updates the existing list.
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Run Code
Output
UNIT IV Page 26
CCS 62 – PYTHON PROGRAMMING
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Run Code
Output
If you need to access individual elements of a list in the reverse order, it's better to use
Output
Linux
macOS
Windows
UNIT IV Page 27
CCS 62 – PYTHON PROGRAMMING
LIST PERMUTATIONS
In Python, you can generate permutations of a list using the permutations() function
provided by the itertools module. Here's an example:
import itertools
my_list = [ 1 , 2 , 3 ]
print (permutations)
Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
In this example, we import the itertools module, create a list my_list containing the
values [1, 2, 3], and generate a list of permutations using the permutations() function. The
permutations() function takes an iterable (in this case, my_list) and returns an iterator that
produces all possible permutations of the iterable.
Note that the permutations() function returns an iterator, not a list. To convert the
iterator to a list, we use the list() constructor. Also note that the permutations are returned as
tuples, not lists.
If you want to generate permutations of a specific length, you can pass the length as the
second argument to the permutations() function. For example:
import itertools
my_list = [ 1 , 2 , 3 ]
print (permutations)
Output:
cssCopy code
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
UNIT IV Page 28
CCS 62 – PYTHON PROGRAMMING
LIST PERMUTATIONS
The permutations of a list simply mean finding out all the combinations (ordering-based)
of the elements inside a set or a list. This practice is greatly used in mathematics and calculus.
However, it is not limited to mathematics/calculus as it is also used in modern-day programming
to perform data manipulations and analytics.
To do this, python has a library “itertools” which provides various functions to help the
users perform various mathematical operations, including “permutations” of a set or a list.
What is the itertools.permutations() Method?
The “permutations()” method inside the itertools library is used to take a list as input and
returns the permutations object as the return value. To understand this method, take a look at the
following syntax:
itertools.permutations (listVar, r)
In this syntax:
UNIT IV Page 29
CCS 62 – PYTHON PROGRAMMING
import itertools
intList = [2,6,8]
After that, simply call the permutations() method and pass in the intList variable and convert the
result into a List and store it inside a variable:
result = list(itertools.permutations(intList))
After that simply print the “result” variable onto the terminal using the following print statement:
print(result)
Running the above code will create the following output on the terminal:
All of the possible permutations have been printed onto the terminal
import itertools
intList = [2,6,8]
UNIT IV Page 30
CCS 62 – PYTHON PROGRAMMING
result = list(itertools.permutations(intList,2))
print(result)
In this code, the tuple size has been passed as “2” and running this code produces the following
output:
From the output, it can be easily observed that all possible permutations have been printed out on
the terminal while keeping the size of a tuple at “2”.
import itertools
textString = "ABCD"
result = list(itertools.permutations(textString))
print(result)
UNIT IV Page 31
CCS 62 – PYTHON PROGRAMMING
Running this code snippet will produce the following permutations on the terminal:
This proves that Python can be used to find the permutations of all the characters of a string.
Conclusion
The itertools package comes by default with Python installation. This package contains
the permutations() method that can be used to calculate all the possible permutations of a list in
python. The list can be of any type (integer, string, characters). This post has gone over the
syntax and the usage of the permutations() method from the itertools package.
In Python, you can use the random module to randomly permute a list. Here's an example
code snippet:
python
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
UNIT IV Page 32
CCS 62 – PYTHON PROGRAMMING
The shuffle() function of the random module takes a list as an argument and shuffles the
list in-place, meaning it modifies the original list instead of creating a new one. If you want to
create a new randomly permuted list without modifying the original list, you can use the
sample() function of the random module:
python
import random
my_list = [1, 2, 3, 4, 5]
print(new_list)
This will output a randomly permuted list like [2, 5, 3, 4, 1]. The sample() function
returns a new list of the same length as the input list, containing a random selection of elements
from the input list.
UNIT IV Page 33