0% found this document useful (0 votes)
38 views17 pages

Unit IV Python

Uploaded by

ezhilvijai4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
38 views17 pages

Unit IV Python

Uploaded by

ezhilvijai4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

PYTHON UNIT IV

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.

List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
thislist = ["apple", "banana", "cherry"]
print(thislist)
O/P
['apple', 'banana', 'cherry']
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

GOVT ARTS AND SCIENCE COLLEGE Page 1


PYTHON UNIT IV

O/P
3
List Items - Data Types
List items can be of any data type:
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
O/P
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
A list can contain different data
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
O/P ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
O/P <class 'list'>
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
O/P
['apple', 'banana', 'cherry']
Python Collections (Arrays)

GOVT ARTS AND SCIENCE COLLEGE Page 2


PYTHON UNIT IV

There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.
Access Python List Elements
In Python, each item in a list is associated with a number. The number is known as a list index.
We can access elements of an array using the index number (0, 1, 2 …). For example,
languages = ["Python", "Swift", "C++"]
# access item at index 0
print(languages[0]) # Python
# access item at index 2
print(languages[2]) # C++
Output:
Python
C++
In the above example, we have created a list named languages.

List Indexing in Python


Here, we can see each list item is associated with the index number. And, we have used the index
number to access the items.
Note: The list index always starts with 0. Hence, the first element of a list is present at index 0,
not 1.

GOVT ARTS AND SCIENCE COLLEGE Page 3


PYTHON UNIT IV

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
Output
C++
Python

Python Negative Indexing


Note: If the specified index does not exist in the list, Python throws the IndexError exception.
Slicing of a Python List
In Python it is possible to access a section of items from the list using the slicing operator :, not
just a single item. For example,
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# items from index 2 to index 4
print(my_list[2:5])
# items from index 5 to end
print(my_list[5:])

GOVT ARTS AND SCIENCE COLLEGE Page 4


PYTHON UNIT IV

# items beginning to end


print(my_list[:])
Output
['o', 'g', 'r']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Here,
 my_list[2:5] returns a list with items from index 2 to index 4.
 my_list[5:] returns a list with items from index 1 to the end.
 my_list[:] returns all list items
Note: When we slice lists, the start index is inclusive but the end index is exclusive.
Add Elements to a Python List
Python List provides different methods to add items to a list.
1. Using append()
The append() method adds an item at the end of the list. For example,
numbers = [21, 34, 54, 12]
print("Before Append:", numbers)
# using append method
numbers.append(32)
print("After Append:", numbers)
Output
Before Append: [21, 34, 54, 12]
After Append: [21, 34, 54, 12, 32]
In the above example, we have created a list named numbers. Notice the line,
numbers.append(32)
Here, append() adds 32 at the end of the array.
2. Using extend()
We use the extend() method to add all items of one list to another. For example,
prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)
even_numbers = [4, 6, 8]

GOVT ARTS AND SCIENCE COLLEGE Page 5


PYTHON UNIT IV

print("List2:", even_numbers)
# join two lists
prime_numbers.extend(even_numbers)

print("List after append:", prime_numbers)


Output
List1: [2, 3, 5]
List2: [4, 6, 8]
List after append: [2, 3, 5, 4, 6, 8]
In the above example, we have two lists named prime_numbers and even_numbers. Notice the
statement,
prime_numbers.extend(even_numbers)
Here, we are adding all elements of even_numbers to prime_numbers.
Change List Items
Python lists are mutable. Meaning lists are changeable. And, we can change items of a list by
assigning new values using = operator. For example,
languages = ['Python', 'Swift', 'C++']
# changing the third item to 'C'
languages[2] = 'C'
print(languages) # ['Python', 'Swift', 'C']
Here, initially the value at index 3 is 'C++'. We then changed the value to 'C' using
languages[2] = 'C'
Remove an Item From a List
1. Using del()
In Python we can use the del statement to remove one or more items from a list. For example,
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
# deleting the second item
del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']
# deleting the last item
del languages[-1]

GOVT ARTS AND SCIENCE COLLEGE Page 6


PYTHON UNIT IV

print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']


# delete first two items
del languages[0 : 2] # ['C', 'Java', 'Rust']
print(languages)
Output
['Python', 'C++', 'C', 'Java', 'Rust', 'R']
['Python', 'C++', 'C', 'Java', 'Rust']
['C', 'Java', 'Rust']
2. Using remove()
We can also use the remove() method to delete a list item. For example,
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
# remove 'Python' from the list
languages.remove('Python')
print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']
Output
['Swift', 'C++', 'C', 'Java', 'Rust', 'R']
Here, languages.remove('Python') removes 'Python' from the languages list.

Python List Methods


Python has many useful list methods that makes it really easy to work with lists.

Method Description

append() add an item to the end of the list

extend() add items of lists and other iterables to the end of the list

insert() inserts an item at the specified index

remove() removes item present at the given index

GOVT ARTS AND SCIENCE COLLEGE Page 7


PYTHON UNIT IV

pop() returns and removes item present at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list

Iterating through a List


We can use the for loop to iterate over the elements of a list. For example,
languages = ['Python', 'Swift', 'C++']
# iterating through the list
for language in languages:
print(language)
Output
Python
Swift
C++

Check if an Item Exists in the Python List


We use the in keyword to check if an item exists in the list or not. For example,
languages = ['Python', 'Swift', 'C++']

print('C' in languages) # False


print('Python' in languages) # True
o/p

GOVT ARTS AND SCIENCE COLLEGE Page 8


PYTHON UNIT IV

False
True
Here,
 'C' is not present in languages, 'C' in languages evaluates to False.
 'Python' is present in languages, 'Python' in languages evaluates to True.

Python List Length


In Python, we use the len() function to find the number of elements present in a list. For
example,
languages = ['Python', 'Swift', 'C++']

print("List: ", languages)

print("Total Elements: ", len(languages)) #3


Run Code
Output
List: ['Python', 'Swift', 'C++']
Total Elements: 3
Python List Comprehension
List comprehension is a concise and elegant way to create lists.
A list comprehension consists of an expression followed by the for statement inside square
brackets.
Here is an example to make a list with each item being increasing by power of 2.
numbers = [number*number for number in range(1, 6)]
print(numbers)
# Output: [1, 4, 9, 16, 25]
Run Code
In the above example, we have used the list comprehension to make a list with each item being
increased by power of 2. Notice the code,
[number*x for x in range(1, 6)]
The code above means to create a list of number*number where number takes values from 1 to 5

GOVT ARTS AND SCIENCE COLLEGE Page 9


PYTHON UNIT IV

The code above,


numbers = [x*x for x in range(1, 6)]
is equivalent to
numbers = []

for x in range(1, 6):


numbers.append(x * x)

Python List Operations


The concatenation (+) and repetition (*) operators work in the same way as they were working
with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

Let's see how the list responds to various operators.

1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
Code

1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)

Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

GOVT ARTS AND SCIENCE COLLEGE Page 10


PYTHON UNIT IV

2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code

1. # concatenation of two lists


2. # declaring the lists
3. list1 = [12, 14, 16, 18, 20]
4. list2 = [9, 10, 32, 54, 86]
5. # concatenation operator +
6. l = list1 + list2
7. print(l)

Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length
It is used to get the length of the list
Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
4. # finding length of the list
5. len(list1)

Output:

4. Iteration
The for loop is used to iterate over the list elements.
Code

1. # iteration of the list


2. # declaring the list
3. list1 = [12, 14, 16, 39, 40]

GOVT ARTS AND SCIENCE COLLEGE Page 11


PYTHON UNIT IV

4. # iterating
5. for i in list1:
6. print(i)

Output:

12
14
16
39
40

5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code

1. # membership of the list


2. # declaring the list
3. list1 = [100, 200, 300, 400, 500]
4. # true will be printed if value exists
5. # and false if not
6.
7. print(600 in list1)
8. print(700 in list1)
9. print(1040 in list1)
10.
11. print(300 in list1)
12. print(100 in list1)
13. print(500 in list1)

Output:

False
False
False
True
True
True

Iterating a List

GOVT ARTS AND SCIENCE COLLEGE Page 12


PYTHON UNIT IV

A list can be iterated by using a for - in loop. A simple list containing four strings, which can be
iterated as follows.
Code

1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each element in each iteration.

5. print(i)

Output:

John
David
James
Jonathan

Python List Functions


 sort(): Sorts the list in ascending order.
 type(list): It returns the class type of an object.
 append(): Adds one element to a list.
 extend(): Adds multiple elements to a list.
 index(): Returns the first appearance of a particular value.
 max(list): It returns an item from the list with a max value.
 min(list): It returns an item from the list with a min value.
 len(list): It gives the overall length of the list.
 clear(): Removes all the elements from the list.
 insert(): Adds a component at the required position.
 count(): Returns the number of elements with the required value.
 pop(): Removes the element at the required position.
 remove(): Removes the primary item with the desired value.
 reverse(): Reverses the order of the list.
 copy(): Returns a duplicate of the list.

GOVT ARTS AND SCIENCE COLLEGE Page 13


PYTHON UNIT IV

Generating prime numbers with list


# Initialize a list
primes = []for possiblePrime in range(2, 21):

# Assume number is prime until shown it is not.


isPrime = True
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = False

if isPrime:
primes.append(possiblePrime)
Python List Permutations
Python has a built-in data type called list. It is like a collection of arrays with different
methodology. Data inside the list can be of any type say, integer, string or a float value, or even a
list type. The list uses comma-separated values within square brackets to store data. Lists can be
defined using any variable name and then assigning different values to the list in a square
bracket. The list is ordered, changeable, and allows duplicate values. For example,
list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]
We all have heard and studied the permutation concept in mathematics, likewise, Python
supports some built-in functions to generate permutations of a list. Python provides a standard
library tool to generate permutations by importing itertools package to implement
the permutations method in python. We will also discuss the recursive method to generate all
possible permutations of a list.
Example Generate Permutations of a list
The below example passes the given list as an argument to itertools.permutations() function. It
defaults to the length of the list and hence generates all possible permutations.
import itertools

GOVT ARTS AND SCIENCE COLLEGE Page 14


PYTHON UNIT IV

list1 = [1, 2, 3]

perm = list(itertools.permutations(list1))

print(perm)

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
Example: Generate successive 'r' length permutations of a list
The below example passes the given list and length as an argument
to itertools.permutations() function. It generates the permutations of the given length.
import itertools
list1 = [1, 2, 3]
r=2
perm = list(itertools.permutations(list1, r))
print(perm)

[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Example: Generate Permutations of a list
The below example takes an empty list to store all permutations of all possible length of a given
list. extend() function is used to add items to the empty list one after the other. Iterating over the
elements of the list using for loop, the itertools.permutations() function finds all the possible
lengths.
import itertools

list1 = [1, 2, 3]

perm = []

for i in range(1,len(list1)+1):
perm.extend(list(itertools.permutations(list1, r=i)))

GOVT ARTS AND SCIENCE COLLEGE Page 15


PYTHON UNIT IV

print(perm)

[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1,
2), (3, 2, 1)]
Sorting
The Python language, like many other high-level programming languages, offers the ability to
sort data out of the box using sorted(). Here’s an example of sorting an integer array:
array = [8, 2, 6, 4, 5]
sorted(array)
[2, 4, 5, 6, 8]
You can use sorted() to sort any list as long as the values inside are comparable.
Search an Element in a List of n Elements
After modifying previous program, I've created another program, that is the program given
below. This program allows user to define the size of list along with its element and the element
that is going to be search from the given list. Let's take a look at the program and its sample run
given below:
mylist = list()

print("Enter the size of list: ", end="")


tot = int(input())

print("Enter", tot, "elements for the list: ", end="")


for i in range(tot):
mylist.append(input())

print("\nEnter an element to be search: ", end="")


elem = input()

for i in range(tot):
if elem == mylist[i]:
print("\nElement found at Position:", i+1)

GOVT ARTS AND SCIENCE COLLEGE Page 16


PYTHON UNIT IV

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]

GOVT ARTS AND SCIENCE COLLEGE Page 17

You might also like