Python tuples

Share me please

Creating tuples

[cc lang=”python”]
# creating tuple
# look the difference in syntax between tuple and list
tuple = ( “item 1”, “item 2”, “item 3”, 2, 3, 4)
print(tuple)
print(type(tuple))

# creating one element tuple this way
tuple = (“item 1”,)
print(tuple)
print(type(tuple))

# this way will not work
tuple = (“item 1”)
print(tuple)
print(type(tuple))
[/cc]

How to index tuples in python

[cc lang=”python”]
# creating tuple
# look the difference in syntax between tuple and list
tuple = ( “item 1”, “item 2”, “item 3”, 2, 3, 4)
print(tuple)
print(type(tuple))

# creating one element tuple this way
tuple = (“item 1”,)
print(tuple)
print(type(tuple))

# this way will not work
tuple = (“item 1”)
print(tuple)
print(type(tuple))
[/cc]

Standard operations with python tuples

[cc lang=”python” height=”440px”]
# indexing tuple
tuple1 = ( “item 0”, “item 1”, “item 2”, “item 1”, “item 1”)
print(tuple)
tuple2 = (“item 3”, “item 4”, “item 5”)
print(tuple2)

# joining tuples
tuple3 = tuple1 + tuple2
print(tuple3)

# you cannot delete element from tuple but you can delete the whole tuple
del tuple3
# uncomment to see the error
# print(tuple3)

# count number of elements with given value
print(tuple1.count(“item 1”))

# find position of searched value
print(tuple1.index(“item 2”))

# uncomment to see what will happen when the value does not exist
#print(tuple1.index(“any any”))

[/cc]