[go: up one dir, main page]

0% found this document useful (0 votes)
71 views33 pages

Unit Iv Python

1. Lists are a mutable data type in Python that can store sequences of different data types. Lists are defined using square brackets [] and elements are separated by commas. 2. Some key characteristics of lists are that they are ordered, elements can be accessed by index, and lists are mutable. The valid indices of a list start at 0 and go up to the length of the list minus 1. 3. List elements can be sliced using start:stop:step indices to extract subsets of the list. Negative indices also allow accessing elements from the end of the list.

Uploaded by

Pavin Pavin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views33 pages

Unit Iv Python

1. Lists are a mutable data type in Python that can store sequences of different data types. Lists are defined using square brackets [] and elements are separated by commas. 2. Some key characteristics of lists are that they are ordered, elements can be accessed by index, and lists are mutable. The valid indices of a list start at 0 and go up to the length of the list minus 1. 3. List elements can be sliced using start:stop:step indices to extract subsets of the list. Negative indices also allow accessing elements from the end of the list.

Uploaded by

Pavin Pavin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

CCS 62 – PYTHON PROGRAMMING

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:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

UNIT IV Page 1
CCS 62 – PYTHON PROGRAMMING

Characteristics of Lists

The list has the following characteristics:

o The lists are ordered.

o The element of the list can access by index.

o The lists are the mutable type.

o The lists are mutable types.

o A list can store the number of various elements.

Ordered List Checking

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

List Indexing and Splitting

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)

o The start denotes the starting index position of the list.

o The stop denotes the last index position of the list.

o The step is used to skip the nth element within a start:stop

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.

Consider the following example:

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

1. # negative indexing example


2. list = [1,2,3,4,5]
3. print(list[-1])
4. print(list[-3:])
5. print(list[:-1])
6. print(list[-3:-1])

Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

LIST ASSIGNMENT AND EQUIVALENCE IN PYTHON

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.

# create two lists with different elements


list3 = [1, 2, 3]
list4 = [1, 4, 3]
# test for list equivalence using the equality operator
if list3 == list4:
print("The lists are equivalent")
else:
print("The lists are not 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

LIST BOUNDS IN PYTHON

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

LIST SLICING IN PYTHON

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]

# Show original list


print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

# Display sliced list


print(List[3:9:2])

# Display sliced list


print(List[::2])

# Display sliced list


print(List[::])

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

# Show original list


print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

# Display sliced list


print(List[::-1])

# Display sliced list


print(List[::-3])

# Display sliced list


print(List[:1:-2])

Output:
Original List:
['Geeks', 4, 'geeks !']

Sliced Lists:
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']

A 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 value according to a reversed
list if the IndexJump value is negative.

Example 3:

# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Show original list


print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

# Creating new List


newList = List[:3]+List[7:]

UNIT IV Page 9
CCS 62 – PYTHON PROGRAMMING

# Display sliced list


print(newList)

# Changing existing List


List = List[::2]+List[1::2]

# Display sliced list


print(List)

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.

LISTS AND FUNCTIONS

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

S.no Method Description

1 append() Used for appending and adding elements to the end of the List.

2 copy() It returns a shallow copy of a list

3 clear() This method is used for removing all items from the list.

4 count() This methods count the elements

UNIT IV Page 10
CCS 62 – PYTHON PROGRAMMING

S.no Method Description

5 extend() Adds each element of the iterable to the end of the List

6 index() Returns the lowest index where the element appears.

7 insert() Inserts a given element at a given index in a list.

8 pop() Removes and returns the last value from the List or the given index value.

9 remove() Removes a given object from the List.

10 reverse() Reverses objects of the List in place.

11 sort() Sort a List in ascending, descending, or user-defined order

12 min() Calculates minimum of all the elements of List

13 max() Calculates maximum of all the elements of List

Adding Element in List


append()

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

# Adds List Element as value of List.

List = ['Mathematics', 'chemistry', 1997, 2000]

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 = ['Mathematics', 'chemistry', 1997, 2000]

# Insert at index 2 value 10087

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]

# Add List2 to List1

List1.extend(List2)

print(List1)

# Add List1 to List2 now

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:

List = ['gfg', 'abc', 3]

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

min(iterable, *iterables[, key])

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

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

print(List.pop())

Output:
2.5

List = [2.3, 4.445, 3, 5.33, 1.054, 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]

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

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 = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

List.remove(3)

print(List)

Output:
[2.3, 4.445, 5.33, 1.054, 2.5]

PRIME GENERATION WITH A LIST

 To generate prime numbers using a list in Python, we can use the following algorithm:

a. Create an empty list to hold the prime numbers.


b. Loop through a range of numbers, starting from 2 (since 1 is not a prime number).
c. For each number, check if it is divisible by any of the prime numbers already found.
d. If it is not, then it is a prime number and should be added to the list.
e. Continue looping through numbers until the desired number of primes have been found.

Here is an example implementation of this algorithm in Python:

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

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.

LIST SORTING IN PYTHON

Definition and Usage

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:

The sort() method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

Syntax
list.sort(reverse=True|False, key=myFunc)

Example

Sort the list alphabetically:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

Parameter Values

UNIT IV Page 20
CCS 62 – PYTHON PROGRAMMING

Parameter Description

reverse Optional. reverse=True will sort the list descending. Default is


reverse=False

key Optional. A function to specify the sorting criteria(s)

More Examples
Example

Sort the list descending:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort(reverse=True)

Example

Sort the list by the length of the values:

# A function that returns the length of the value:


def myFunc(e):
return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc)

UNIT IV Page 21
CCS 62 – PYTHON PROGRAMMING

Example

Sort a list of dictionaries based on the "year" value of the dictionaries:

# A function that returns the 'year' value:


def myFunc(e):
return e['year']

cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]

cars.sort(key=myFunc)

OUTPUT:

[{'car': 'Mitsubishi', 'year': 2000}, {'car': 'Ford', 'year': 2005},


{'car': 'VW', 'year': 2011}, {'car': 'BMW', 'year': 2019}]

Example

Sort the list by the length of the values and reversed:

# A function that returns the length of the value:


def myFunc(e):
return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(reverse=True, key=myFunc)

OUTPUT:

UNIT IV Page 22
CCS 62 – PYTHON PROGRAMMING

FLEXIBLE SORTING IN PYTHON

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:

Sort a list of integers in ascending order:

my_list = [5, 2, 8, 1, 9]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 5, 8, 9]

Sort a list of strings in descending order:

my_list = ['apple', 'banana', 'cherry', 'date']


sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: ['date', 'cherry', 'banana', 'apple']

Sort a list of tuples by the second element in ascending order:

my_list = [('apple', 3), ('banana', 1), ('cherry', 2), ('date', 4)]


sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [('banana', 1), ('cherry', 2), ('apple', 3), ('date', 4)]

Sort a dictionary by value in descending order:

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}


sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))
print(sorted_dict) # Output: {'date': 4, 'apple': 3, 'cherry': 2, 'banana': 1}

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.

LIST SEARCHING 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

Using the in operator:


The in operator is a simple way to check if an item is present in a list. You can use it like this:
my_list = [1, 2, 3, 4, 5] if 3 in my_list: print("Found!")
Output: Found!
In this example, we create a list my_list with five integer values. We then use the in
operator to check if the value 3 is present in the list. If it is, we print "Found!".
The in operator can also be used with strings, tuples, and other sequence types in Python.
Using the index() method:
If you need to know the index (position) of an item in a list, you can use the index()
method. Here's an example:
my_list = [1, 2, 3, 4, 5] index = my_list.index(3) print(index)
Output: 2
In this example, we create a list my_list and use the index() method to find the index of
the value 3. The method returns the index 2, which we then print to the console.
Note that if the item is not found in the list, the index() method will raise a ValueError
exception. You can handle this exception using a try-except block.
Using a loop:
If you need to do something more complex when searching for an item, you can use a
loop to iterate over the list and check each item individually. Here's an example:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
if item == 3:
print("Found!")
Output: Found!
In this example, we use a for loop to iterate over the items in the list my_list. For each
item, we check if it is equal to 3. If it is, we print "Found!".
This approach gives you more flexibility than the previous two methods because you can
perform any operation you want on the item, not just checking if it exists.

UNIT IV Page 24
CCS 62 – PYTHON PROGRAMMING

Using the filter() function:


The filter() function is a built-in function in Python that can filter a sequence (like a list)
based on a given condition. Here's an example of using filter() to search for an item in a list:

my_list = [1, 2, 3, 4, 5] result = filter(lambda x: x == 3, my_list) if len(list(result)) > 0:


print("Found!")
Output: Found!
In this example, we use the filter() function to filter the list my_list based on the
condition that x == 3. The result is an iterator, so we convert it to a list and check if the length of
the list is greater than zero (i.e., if any items were found).
The filter() function can be useful if you need to perform more complex filtering
operations, but it can be slower than other methods for simple searches.

REVERSING A LIST

The reverse() method reverses the elements of the list.


Example

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# reverse the order of list elements


prime_numbers.reverse()

print('Reversed List:', prime_numbers)

# Output: Reversed List: [7, 5, 3, 2]


Run Code

Syntax of List reverse()

The syntax of the reverse() method is:

UNIT IV Page 25
CCS 62 – PYTHON PROGRAMMING

list.reverse()

reverse() parameter

The reverse() method doesn't take any arguments.

Return Value from reverse()

The reverse() method doesn't return any value. It updates the existing list.

Example 1: Reverse a List

# Operating System List


systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# List Reverse
systems.reverse()

# updated list
print('Updated List:', systems)
Run Code

Output

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']

There are other several ways to reverse a list.

Example 2: Reverse a List Using Slicing Operator

# Operating System List


systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

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

Original List: ['Windows', 'macOS', 'Linux']


Updated List: ['Linux', 'macOS', 'Windows']

Example 3: Accessing Elements in Reversed Order

If you need to access individual elements of a list in the reverse order, it's better to use

the reversed() function.


# Operating System List
systems = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order


for o in reversed(systems):
print(o)
Run Code

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 ]

permutations = list (itertools.permutations(my_list))

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 ]

permutations = list (itertools.permutations(my_list, 2 ))

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

In this example, we generate permutations of length 2 by passing the value 2 as the


second argument to the permutations() function. This produces all possible pairs of elements
from the original list.

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:

 listVar is the list variable that will be used to calculate permutations


 r is the length of each tuple in the output
Note: It is a good practice to change the returned output into a list by applying the list() method
to it. Doing this will make the output readable.
How to Find Permutations of a Numeric List in Python?
To find the permutations of a numeric list, import the itertools library and create an integer list
using the following line:

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

How to Find Permutations of a List With Fixed Tuple Length?


The user can put a limit on the size of each tuple by passing in length in the permutations
method’s second argument. To demonstrate this, take the following code:

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”.

How to Find Permutations of a String in Python?


A string in python is also considered to be a “list”, which basically means that a string
can be passed into the permutations method, and all of its individual characters will be used to
create possible permutations. To demonstrate this, take the following code snippet:

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.

RANDOMLY PERMUTING A LIST IN PYTHON

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

This will output a randomly permuted list like [3, 2, 5, 1, 4].

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]

new_list = random.sample(my_list, len(my_list))

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

You might also like