Python Tuples

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 6

Tuples

• Definition : A tuple is a finite ordered list of possible different values


which are used to bundle related values together.
• A tuple is defined by values separated by commas enclosed within
parentheses().
• Syntax for Creating Tuple :
• tuple_name=(item_1, item_2, item_3 …., item_n)
• f1=(“Ferrari”, “mercedes”, “renault”, “PSA”)
• The contents and order of items in tuple are the same as they were
when the tuple was created.
• Empty tuple can be created as follows
• >>>empty_tuple = ()
• A tuple with one item is constructed by having a value followed by a
comma.
>>>single_var =‘hello’,
>>>single_var
(‘hello’,)
• Basic Tuple Operations: • Comparison operations
- Concatenation : >>>tuple_1 == tuple_2
- Eg: tuple_1 = (1,3,5,7) • False
- tuple_2 = (2,4,6,8)
>>>tuple_1 != tuple_2
- tuple_1 + tuple_2
• True
- (1,3,5,7,2,4,6,8)
- Repeat number of times: >>>tuple_1 >= tuple_2
Repetition can be achieved • False
using the multiplication symbol. >>>tuple_1 <= tuple_2
- Eg: tuple_1 * 2 • True
- (1,3,5,7,1,3,5,7)
- Membership Operators:
- Eg: 9 in tuple_1
Comparisons supported are
- False
(==, !=, >=, <=, >, <)
- 10 not in tuple_1
- True
• Creating a tuple:
• The built-in function tuple() is used to create a tuple.
• Syntax : tuple([sequence])
• Eg:
>>> variable= “RAJA”
>>> type(variable)
<class ‘str’>
>>> variable2 = tuple(variable)
>>>type(variable2)
<class ‘tuple’>

• We have to convert lists and strings to tuples using tuple() function before concatenation.
• We can have one tuple inside another. Such a tuple is called Nested tuple.
Eg: var2 = (1,3,5,7)
Var 3 = (2,4,6,8)
Nested_var = (var2, var3)
>>>nested_var
((1,3,5,7) , (2,4,6,8))
• Indexing and Slicing in Tuples:
• We can access each item in tuple using indexing.
• Eg: tuple_1 = (“Rose”, “Lotus”, “Sunflower”, “Lilly”, “Hibiscus”)
• Syntax : tuple_name[index]
>>>tuple_1[2]
Rose Lotus Sunflower Lilly Hibiscus
‘Sunflower’
>>>tuple_1[4] 0 1 2 3 4
‘hibiscus’
If we access an element not in the tuple, we get a tuple index out of range error.

Rose Lotus Sunflower Lilly Hibiscus


>>>tuple_1[-3]
‘Sunflower’ -5 -4 -3 -2 -1
• Slicing
• Syntax : tuple_name[start: stop: step]
• Tuple slicing returns a part of the tuple from the start index to the stop index
value, which includes the start index value but excludes the stop index value.
V I B G Y O R
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1

>>> colors = (“V”, “I”, “B”, “G”, “Y”, “O”, “R”)


>>>colors
(‘V’, ‘I’, ‘B’, ‘G’, ‘Y’, ‘O’, ‘R’)
>>>colors[1:4]
(‘I’, ‘B’, ‘G’)
>>>colors[::]
(‘V’, ‘I’, ‘B’, ‘G’, ‘Y’, ‘O’, ‘R’)
>>>colors[1:5:2]
(‘I’, ‘G’)
>>>colors[::-1]
(‘R’, ‘O’, ‘Y’, ‘G’, ‘B’, ‘I’, ‘V’)
>>>colors[-5:-2]
(‘B’, ‘G’, ‘Y’)

You might also like