Python: Lists (difference between Lists and Tuples)

#Lecture 6 Lists

”’

Lists look like Tuples, but they have some critical differences. It’s very important to make out the differences

Tuples Lists

===================== ===================================

used () parenthesis Uses [] parenthesis

singlets need , (5,) No additional comma reqired [5]

Immutable, means elements can’t Important feature, Lists are mutable

be modified e.x.,: Trees=[‘Mango’, ‘Neem’, ‘Tamarind’]

we can replace Neem i.e. Trees[1]=’Banian’

Now Trees List will looks as

Trees=[‘Mango’, ‘Banian’, ‘Tamarind’]

”’

Trees=[‘Mango’, ‘Neem’, ‘Tamarind’]

Fruits=[‘Apple’, ‘Banana’]

print Trees, Fruits

#Modify the Trees lists

Trees[1]=’Banian’

print Trees

#using methods like append, we can extend Lists

Fruits.append(‘Mango’)

print Fruits

#Now we will see another example called “Aliasng”

Plants=[Trees,Fruits]

Plants1=[[‘Mango’, ‘Banian’, ‘Tamarind’], [‘Apple’, ‘Banana’, ‘Mango’]]

#if you print both look alike

#print Plants

#print Plants1

#Now modify Trees lists using append method

Trees[1]=’Neem’

print Plants

print Plants1

”’

OUTPUTs varies

Plants output [[‘Mango’, ‘Neem’, ‘Tamarind’], [‘Apple’, ‘Banana’, ‘Mango’]]

Plants1 output [[‘Mango’, ‘Banian’, ‘Tamarind’], [‘Apple’, ‘Banana’, ‘Mango’]]

”’

python – oddTuples

#Python Function which returns odd Tuples

”’

Write a procedure called oddTuples, which takes a tuple as input,

and returns a new tuple as output, where every other element of the input tuple is copied,

starting with the first one. So if test is the tuple (‘I’, ‘am’, ‘a’, ‘test’, ‘tuple’),

then evaluating oddTuples on this input would return the tuple (‘I’, ‘a’, ‘tuple’).

”’

def oddTuples(aTup):

”’

aTup: a tuple

returns: tuple, every other element of aTup.

”’

# Your Code Here

num=1

t1=()

for i in aTup:

if num%2 == 1:

t1= t1+(i,)

num+=1

else:

num+=1

return t1

print oddTuples((1, ‘two’, 3, ‘four’, 5))

python programme to calculate greatest common divisior (GCD) using recursion

def gcdIter(a, b):

”’

a, b: positive integers

returns: a positive integer, the greatest common divisor of a & b.

”’

# Your code here

Recursive Method

 if a == b:

 return a

  elif a > b:

 return gcdIter(a-b, b)

elif b > a:

return gcdIter(a, b-a)