Sunday, July 29, 2018

Lesson-4 : Tuples


This blog assumes that you have a Linux machine with Python already installed. 
If you don't, then you can use an AWS cloud based image that has Python. For help, refer to my blog
I am using Python 2.7 for this tutorial.

TUPLES


Tuples are lists that are IMMUTABLE; meaning, you can NOT change the objects in a tuple.

They can hold objects of different data types.


Example Program - 5:
************************************************************

#! /bin/python

tup = ('This','is a','frozen','list')

print "\n tup = ", tup

print "\n tup[2] = ", tup[2]   # The indexing starts at zero.

************************************************************








Try to change the value of an item in a tuple and see what happens.

tup[2] = 34

Example Program - 6:
*************************************************************
#! /bin/python

tup1 = (6,5,4)

tup2 = tup1 + (3,2,1)

print "\n tup2 [3:5] = ", tup2 [3:5]

print "\n tup2[5] =", tup2[-2]    # Check if this returns correct value

# Type cast a list into a tuple

list1 = ["i","am","a","list"]

tup3 = tuple(list1)

print "\n tup3 = ", tup3

# Check what this returns

print "\n min(tup3) = ", min(tup3)

print "\n max(tup2) = ",max(tup2)

tup4 = tup3 * 3

print "\n tup4 = ", tup4, "\n"


***************************************************************
















EXERCISE - 3

Write a program that
1. Defines a tuple and assigns 6 objects
2. Replaces the 5th item with some other value. (Think about work arounds)



No comments:

Post a Comment

Lesson-6 : Sets and Frozen Sets

This blog assumes that you have a Linux machine with Python already installed.  If you don't, then you can use an AWS cloud base...