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.
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))
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)
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.
print("List2:", even_numbers)
# join two lists
prime_numbers.extend(even_numbers)
Method Description
extend() add items of lists and other iterables to the end of the list
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.
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
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]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
Output:
3. Length
It is used to get the length of the list
Code
Output:
4. Iteration
The for loop is used to iterate over the list elements.
Code
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
Output:
False
False
False
True
True
True
Iterating a List
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
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
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)))
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()
for i in range(tot):
if elem == mylist[i]:
print("\nElement found at Position:", i+1)
Reversing a List
Example
prime_numbers = [2, 3, 5, 7]