GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Sunday, May 8, 2011

Python - Tuple

Introduction

Tuple is like a list. That is it's a container of data. It also can contain different type of data. But the difference of tupple and list is that the tuple data cannot be modified after it's defined. You cannot modify or delete an element in the tuple. There's some data structure that suitable used tuple than list. For example the day names in a week, the month names in a year, the songs of lady gaga monster ball album. The different things a gain for tuple than list is that tuple definition is using ( and ). Other is same as list.

Program Code

days = ("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday")
print days
print "The length of the days: ", len(days)

Output

("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday")
The length of the days: 7

Accessing The Element

Because there's no feature for modifying or deleting elements of a tuple, so the one operation we can use it is accessing it. We keep using the above example.

Program Code

print days[0]

Output

sunday

For statement in tuple

You don't need to iterate just one by by. But there's a feature that you can use for iterating the all elements once. Here's a code.

Program Code

names = ["lady gaga", "selena holmes", "shakira", "jenifer lopez", "barack obama"]
for item in names:
     print names

Output

lady gaga
selena holmes
shakira
jenifer lopez
barack obama

If Statement In Tuple

You can using if to test whether some data exist on tuple or not. For example we can test whether "tony blair" exists or not on the data.

Program Code

names = ["shakira", "selena holmes", "lady gaga"]
if "tony blair" in names:
    print "Tony Blair exists on data"
else:
    print "Tony Blair doesn't exists on data"

Output

Tony Blair doesn't exists on data


Share/Bookmark

No comments:

Post a Comment