Krivalar Tutorials 
Krivalar Tutorials


Python tuple - function, tuple indexing, slicing, empty tuple



<List    Start from Beginning >







  • The tuple contains an ordered collection of items of different data types.
  • In a tuple, items are separated by a comma.
  • The tuple is enclosed by the parentheses(()).
  • Tuples are immutable. Once created, we can't change the item's value and size of the tuple.
  • The tuple is a read-only data structure.



Syntax of Python Tuple

Following syntax is used to declare a tuple.


Tuple_name = (item1, item2 ...itemN)

For Example:

>> Tup=(23,"Varun",20,"Vanathi")
>> # print the tuple
>> print(Tup)
(23, 'Varun', 20, 'Vanathi')
>> type(Tup) # Check the data type of Tup
<class 'tuple'>
>> Tup_1=(25,67,89,90)
>> Tup_1  # to print items from the tuple Tup_1
(25, 67, 89, 90)
>> 

We can also create empty tuples by using the following Syntax.


Tuple_name = ()


For Example:


>> empty_tuple = () # to create an empty tuple 
>> empty_tuple
()
>> type(empty_tuple) # to check the tuple type
<class 'tuple'>



Basic Operation on Python - Tuples

  • We can use the ' + ' operator for concatenation operation.
  • Also, we can use ' * ' for repeating the items in the tuple for the specified number of times.
  • For example:

    >> emp_age = (35,30,45,27,33)
    >> emp_age1 = (28,32,35)
    >> emp_age + emp_age1   # Concatenation  operation
    (35, 30, 45, 27, 33, 28, 32, 35)
    >> # repetition operation
    >> emp_age1 * 2
    (28, 32, 35, 28, 32, 35)
  • We can use the membership operator to check whether the tuple has an item. The output of the membership operator is true or false.
  • For example:

    >> emp_age = (35,30,45,27,33)
    >> 30 in emp_age
    True
    >> 37 in emp_age
    False
    >>
    
  • We can also use a comparison operator to compare two tuples.
  • For example:

    >> emp_age = (35,30,45,27,33)
    >> emp_age1 = (28,32,35)
    >> emp_age == emp_age1
    False
    >> emp_age < emp_age1
    False
    >> emp_age  >  emp_age1
    True
    >>

The tuple() function

  • The tuple() function is used to create a tuple.
  • The syntax of this function is given below.
tuple([sequence])
  • Where sequence can be a number or string or tuple itself.
  • An empty tuple is created by not specifying the sequence.
For example:
>> agent=tuple('arun') # creating tuple
>> empty_agent_list=tuple() #creating empty tuple
>> type(agent)
<class 'tuple'>
>> type(empty_agent_list)
<class 'tuple'>
>> agent     #show the items in agent tuple
('a', 'r', 'u', 'n')
>> num1=tuple((1,2,3))    # create tuple with another tuple
>> num1
(1, 2, 3)
>>

<List    Start from Beginning >





















Searching using Binary Search Tree