tuples and lists are very similar, except that tuples and strings are Immutable that is, you cannot modify tuples. Tuples are defined by a comma-separated list of items in parentheses. Tuples are typically used when a statement or user-defined function can safely take a set of values, that is, the value of the tuple being used does not change.
Working with tuples
#!/usr/bin/python # Filename:using_tuple.py Zoo = (' Wolf ', ' Elephant ', ' penguin ') print ' number of animals in the zoo is ', Len (zoo) New_zoo = (' monkey ', ' Dolphin ', zoo) print ' Number of animals in the new zoo was ', Len (new_zoo) print ' All ANI Mals in New Zoo is ', new_zoo print ' Animals brought from the old Zoo is ', new_zoo[2] print ' Last animal brought from the old zoo Is ', new_zoo[2][2]
How it works
Variable Zoo is a tuple, and we see that the Len function can be used to get the length of the tuple. This also indicates that the tuple is also a sequence.
As the old zoo was closed, we moved the animals to the new zoo. Therefore, the New_zoo tuple contains some animals already there and animals brought from the old zoo. Back to the topic, notice that tuples within tuples do not lose their identities.
You can access the items in a tuple by using a pair of parentheses to indicate the location of an item, just as we use the list. This is called the index operator. We use new_zoo[2] to access the third item in the New_zoo. We use new_zoo[2][2] to access the third item of the third project of the New_zoo tuple. Contains a tuple of 0 or 1 item objectives. An empty tuple consists of a pair of empty parentheses, such as Myempty = (). However, tuples that contain a single element are less simple. the first (only) item must be followed by a comma so that Python can differentiate between tuples and an object with parentheses in the expression. That is, if you want a tuple containing item 2, you should indicate Singleton = (2,).
Meta-Group Printing
The most common use of tuples is in the print statement
#!/usr/bin/python # Filename:print_tuple.py Age = $ name = ' Swaroop ' print '%s is%d years old '% (name, age) print ' W Hy is%s playing with that python? '% name
This article is from the "Thousand Face" blog, please make sure to keep this source http://oslibo.blog.51cto.com/10854638/1713443
Python Data Structures-tuples