HOME - Recent Changes - Search:

Academic Work


Personal

* pot de départ


dblp


(:twitter:)

-----

[ edit | logout ]
[ help | sandbox | passwd ]

Basic Datatypes: Tuples

#############################

Once a tuple is created, it cannot be changed (immutable).

tup = ()   # Empty tuple. Don't use the variable name 'tuple' because it'll shadow a built-in function!

t = ('vader', 'luke', 'leia')
print t[0]   # vader
print t[:-1]   # ('vader', 'luke') , note that the result is a new tuple

print t.index('leia')   # 2
print 'luke' in t   # True

# CONVERSIONS between tuples and lists
t = ('a', 'b')   # a tuple
li = list(t)     # tuple -> list
print li         # ['a', 'b']

tu = tuple(li)   # list -> tuple
print tu         # ('a', 'b')
  • Tuples are faster than lists.
  • If you don't want to change a "list", use a tuple. It makes your code safer.
  • You can use multi-variable assignments by writing a function that returns a tuple of all the values.

A pitfall

singleton = ('jabba')
print type(singleton)     # <type 'str'> , not a tuple!
singleton = ('jabba', )   # notice the comma at the end
print singleton           # ('jabba',) , now it's a tuple

Some tuple functions

countT.count(value) → integer -- return number of occurrences of value
indexT.index(value, [start, [stop]]) → integer -- return first index of value. Raises ValueError if the value is not present.

Some examples

(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
print MONDAY     # 0
print SATURDAY   # 5
Cloud City


anime | bash | blogs | bsd | c/c++ | c64 | calc | comics | convert | cube | del.icio.us | digg | east | eBooks | egeszseg | elite | firefox | flash | fun | games | gimp | google | groovy | hardware | hit&run | howto | java | javascript | knife | lang | latex | liferay | linux | lovecraft | magyar | maths | movies | music | p2p | perl | pdf | photoshop | php | pmwiki | prog | python | radio | recept | rts | scala | scene | sci-fi | scripting | security | shell | space | súlyos | telephone | torrente | translate | ubuntu | vim | wallpapers | webutils | wikis | windows


Blogs and Dev.

* Ubuntu Incident
* Python Adventures
* me @ GitHub


Places

Debrecen | France | Hungary | Montreal | Nancy


Notes

full circle | km


Hobby Projects

* Jabba's Codes
* PmWiki
* Firefox
* PHP
* JavaScript
* Scriptorium
* Tutorials
* me @ GitHub


Quick Links


[ edit ]

View - Edit - History - Attach - Print *** Report - Recent Changes - Search
Page last modified on 2009 October 18, 06:16