List and Tuples
List and Tuples
Lists
List is an ordered sequence of items. Values in the list are called
elements / items.
It can be written as a list of comma-separated items (values)
between square brackets[ ].
Items in the lists can be of different data types.
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
List slices:
List slicing is an operation that extracts a subset of elements from an list and
packages them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
List methods:
syntax:
list name.method name( element/index/list)
List loops:
1. For loop
2. While loop
3. Infinite loop
Syntax:
while (condition):
body of while
Sum of elements in list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Output:
15
3. Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It
keeps on
running. Such loops are called infinite loop.
Example
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output:
Enter the number 10
you entered:10
Enter the number 12
you entered:12
Enter the number 16
you entered:16
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without
entirely recreating it.
An item can be changed in a list by accessing it directly as part of the
assignment statement.
Using the indexing operator (square brackets[ ]) on the left side of an
assignment, one of the list items can be updated.
Aliasing(copying):
Creating a copy of a list is called aliasing. When you create a copy both list
will behaving same memory location. changes in one list will affect another
list.
Alaising refers to having different names for same list values.
In this a single list object is created and modified using the subscript
operator.
When the first element of the list named “a” is replaced, the first element
of the list named “b” is also replaced.
This type of change is what is known as a side effect. This happens
because after the assignment b=a, the variables a andb refer to the exact same
list object.
They are aliases for the same object. This phenomenon is known
as aliasing.
To prevent aliasing, a new object can be created and the contents of the
original can be copied which is called cloning.
Clonning:
To avoid the disadvantages of copying we are using cloning. creating a
copy of asame list of elements with two different memory locations is called
cloning.
Changes in one list will not affect locations of aother list.
Cloning is a process of making a copy of the list without modifying the
original list.
1. Slicing
2. list()method
3. copy() method
List as parameters:
In python, arguments are passed by reference.
If any changes are done in the parameter which refers within the function,
then the changes also reflects back in the calling function.
When a list to a function is passed, the function gets a reference to the list.
Passing a list as an argument actually passes a reference to the list, not a
copy of the list.
Since lists are mutable, changes made to the elements referenced by the
parameter change the same list that the argument is referencing.
Example 1:
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output
[2,3,4,5]
Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Output
inside [11, 12, 13, 14, 15]
outside [11, 12, 13, 14, 15]
Example 3
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
output
[30, 1, 2, 3, 4, 5]
Tuple:
A tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be
used.
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple methods:
Tuple is immutable so changes cannot be done on the elements of a tuple once
it is assigned.
Tuple Assignment:
Tuple assignment allows, variables on the left of an assignment operator
and values of tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each
expression to a target.
Because multiple assignments use tuples to work, it is often termed
tupleassignment.
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as return value:
A Tuple is a comma separated sequence of items.
It is created with or without ( ).
A function can return one value. if you want to return more than one value
from a function. we can use tuple as return value.
Example1:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Output:
enter a value:4
enter b value:3
reminder: 1
quotient: 1
Example2:
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Output:
smallest: 1
biggest: 6
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,'a')
Output:
(2, 3, 'a')
Dictionaries:
Dictionary is an unordered collection of elements. An element in dictionary
has a key: value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Methods in dictionary:
ILLUSTRATIVE PROGRAM
1. SELECTION SORT PROGRAM
data = []
print('Selection Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
for i in range(0,n-1):
small=int(data[i])
pos=i
for j in range(i+1,n):
if int(data[j])<small:
small=int(data[j])
pos=j
temp=data[i]
data[i]=data[pos]
data[pos]=temp
print(data)
print('Sorted Array :')
print(data)
Insertion sort
2. INSERTION SORT PROGRAM
data = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
for i in range(1,n):
temp=int(data[i])
j=i-1
while temp<int(data[j]) and j>=0:
data[j+1]=data[j]
j=j-1
data[j+1]=temp
print(data)
print('Sorted Array is:')
print(data)
3. MERGE SORT PROGRAM
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if int(lefthalf[i]) < int(righthalf[j]):
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
data = []
print('Merge Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
print('Original Array :')
print(data)
print('Intermediate s :')
mergeSort(data)
print('Sorted Array is:')
print(data)
4. HISTOGRAM PROGRAM
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
Output:
**
***
******
*****