9. PYTHON DATA TYPES(cont...) - PYTHON TUPLES

4. Python Tuples:

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: 
1. Lists are enclosed in brackets ( [ ] ) and their elements and size 
can be changed. 
2. Tuples are enclosed in parentheses ( ( ) ) and cannot be updated. 
Tuples can be thought of as read-only lists. 

For example:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )

tinytuple = (123, 'john')
1.print (tuple)               # Prints complete tuple
2. print (tuple[0])         # Prints first element of the tuple
3. print (tuple[1:3])      # Prints elements starting from 2nd till 3rd
4. print (tuple[2:])        # Prints elements starting from 3rd element
5. print (tinytuple * 2)  # Prints tuple two times
6. print (tuple + tinytuple) # Prints concatenated tuple

This produce the following result −
1.('abcd', 786, 2.23, 'john', 70.200000000000003)
2. abcd
3. (786, 2.23)
4. (2.23, 'john', 70.200000000000003)
5. (123, 'john', 123, 'john')
6. ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will 
need a trailing comma to indicate that it is in fact a tuple.

For Example:
# only parentheses is not enough

my_tuple = ("hello")
print(type(my_tuple))  #Output: <class 'str'>

# need a comma at the end

my_tuple = ("hello",)  
print(type(my_tuple))    #Output: <class 'tuple'>

# parentheses is optional

my_tuple = "hello",
print(type(my_tuple))   #Output: <class 'tuple'>

Accessing Elements in a Tuple:
There are various ways in which we can access the elements of 
a tuple.

1. Indexing
We can use the index operator [] to access an item in a tuple
where the index starts from 0.So, a tuple having 6 elements 
will have index from 0 to 5. Trying to access an element other 
that (6, 7,...) will raise an IndexError.

The index must be an integer, so we cannot use float or other
types. This will result into TypeError.

Likewise, nested tuple are accessed using nested indexing.

For Example:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])    #Output: 'p'
print(my_tuple[5])    #Output: 't'

# index must be in range
# If you uncomment line 14, you will get an error.
print(my_tuple[6])    #IndexError: list index out of range

# index must be an integer
my_tuple[2.0]      # TypeError: list indices must be integers, 
not float

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3])   # Output: 's'
print(n_tuple[1][1])   # Output: 4

2. Negative Indexing
Python allows negative indexing for its sequences.The index of
-1 refers to the last item, -2 to the second last item and so on.

For example:
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[-1])   # Output: 't'
print(my_tuple[-6])   # Output: 'p'

3. Slicing
We can access a range of items in a tuple by using the slicing
operator - colon ":".

For Example:
my_tuple = ('p','y','t','h','o','n','1','2','3')

# elements 2nd to 4th
print(my_tuple[1:4])     # Output: ('y', 't', 'h')

# elements beginning to 2nd
print(my_tuple[:-7])     # Output: ('p', 'y')

# elements 8th to end
print(my_tuple[7:])     # Output: ('1', '2')

# elements beginning to end
print(my_tuple[:])      # Output: ('p', 'y', 't', 'h', 'o', 'n', '1', '2', '3')

Changing a Tuple:

Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it
has been assignedBut, if the element is itself a mutable
datatype like list, its nested items can be changed. We can also
assign a tuple to different values (reassignment).

For Example:
my_tuple = (4, 2, 3, [6, 5])

# we cannot change an element
my_tuple[1] = 9   # TypeError: 'tuple' object does not support item
assignment

# but item of mutable element can be changed
my_tuple[3][0] = 9
print(my_tuple)     # Output: (4, 2, 3, [9, 5])

# tuples can be reassigned
my_tuple = ('p','y','t','h','o','n','1','2','3')
print(my_tuple)     # Output: ('p', 'y', 't', 'h', 'o', 'n', '1', '2', '3')

We can use + operator to combine two tuples. This is also
called concatenation.
We can also repeat the elements in a tuple for a given number 
of times using the operatorBoth + and * operations result 
into a new tuple.

For Example:
# Concatenation
print((1, 2, 3) + (4, 5, 6))  # Output: (1, 2, 3, 4, 5, 6)

# Repeat
print(("Repeat",) * 3)    # Output: ('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple
We cannot change the elements in a tuple. That means we 
cannot delete or remove items from a tupleBut deleting a
tuple entirely is possible using the keyword del.

For Example:
my_tuple = ('p','y','t','h','o','n','1','2','3')
# can't delete items
del my_tuple[3]    # TypeError: 'tuple' object doesn't support item 
deletion
del my_tuple   # can delete entire tuple
my_tuple      # NameError: name 'my_tuple' is not defined

Python Tuple Methods:

Methods that add items or remove items are not available with 
tuple. Only the following two methods are available.

MethodDescription
count(x)Return the number of items that is equal to x
index(x)Return index of first item that is equal to x
For Example:
my_tuple = ('a','p','p','l','e',)

# Count
print(my_tuple.count('p'))    # Output: 2

# Index
print(my_tuple.index('l'))    # Output: 3

Built-in Functions with Tuple
FunctionDescription
all()Return True if all elements of the tuple are true (or if the tuple is empty).
any()Return True if any element of the tuple is true. If the tuple is empty, return False.
enumerate()Return an enumerate object. It contains the index and value of all the items of tuple as pairs.
len()Return the length (the number of items) in the tuple.
max()Return the largest item in the tuple.
min()Return the smallest item in the tuple
sorted()Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum()Retrun the sum of all elements in the tuple.
tuple()Convert an iterable (list, string, set, dictionary) to a tuple.

No comments:

Post a Comment