Sunday, May 8, 2011

Python - Tuple


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)


("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]



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


lady gaga
selena holmes
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"
    print "Tony Blair doesn't exists on data"


Tony Blair doesn't exists on data


No comments:

Post a Comment