Showing posts with label Python Tuples. Show all posts
Showing posts with label Python Tuples. Show all posts

Python Tuples || Tuples in python

← Back to Home

๐Ÿงพ Tuples in Python –  Beginner-Friendly 

One of the important data structures in Python is the tuple. In this article, we’ll explore what tuples are, how to use them, and why they’re useful.


✅ What is a Tuple?

A tuple is a collection of items that is:

  • Ordered: Items have a fixed position.

  • Immutable: You cannot change the items after the tuple is created.

  • Allows duplicates: You can have the same value more than once.

Think of a tuple like a list, you can’t modify it after creation.


๐Ÿ“Œ How to Create a Tuple

Creating a tuple is easy! Just use parentheses () and separate the items with commas.

# A tuple with numbers
numbers = (1, 2, 3, 4)

# A tuple with mixed data types
person = ("Alice", 25, "Engineer")

# A tuple with one item (note the comma!)
single_item = (5,)

๐Ÿ” Accessing Tuple Items

You can access tuple items by using their index, starting from 0.

person = ("Alice", 25, "Engineer")

print(person[0])  # Output: Alice
print(person[2])  # Output: Engineer

๐Ÿšซ Tuples are Immutable

Once a tuple is created, you cannot change it:

person = ("Alice", 25, "Engineer")

# This will give an error
# person[1] = 30

If you need a changeable version, consider using a list instead.


๐Ÿ” Looping Through a Tuple

You can loop through a tuple using a for loop:

colors = ("red", "green", "blue")

for color in colors:
    print(color)

๐Ÿ”ง Tuple Methods

Even though tuples are immutable, they have a few useful methods:

  • .count(value) – Returns the number of times a value appears.

  • .index(value) – Returns the index of the first occurrence of the value.

data = (1, 2, 3, 2, 4)

print(data.count(2))  # Output: 2
print(data.index(3))  # Output: 2

๐Ÿ“ฆ Tuple Packing and Unpacking

Packing means putting values into a tuple. Unpacking means assigning values from a tuple to variables.

# Packing
person = ("Bob", 30, "Doctor")

# Unpacking
name, age, job = person

print(name)  # Bob
print(age)   # 30

๐Ÿ“Š When to Use a Tuple?

Use a tuple when:

  • You want to store a fixed collection of items.

  • You want to make sure the data cannot be changed.

  • You need to use the data as a key in a dictionary (tuples can be used as keys, but lists cannot).


✅ Quick Summary

Feature Tuple List
Mutable ❌ No ✅ Yes
Ordered ✅ Yes ✅ Yes
Allows Duplicates ✅ Yes ✅ Yes
Syntax (1, 2, 3) [1, 2, 3]

๐Ÿ“š Example: Tuple in a Real Program

# List of students with their scores (name, score)
students = [
    ("Alice", 85),
    ("Bob", 78),
    ("Charlie", 92)
]

for name, score in students:
    print(f"{name} scored {score} points.")

Watch video to understand tuple in python: 




๐Ÿ’ฌ Final Thoughts

Tuples are a simple yet powerful feature in Python. Once you understand when and why to use them, they can help make your code cleaner, safer, and more efficient.

If you're new to Python, start by practicing with lists and tuples to get a good grip on how Python handles collections of data.

Tuples in Python

← Back to Home

Tuples :


Tuples are immutable list data structures in python. They are like lists but the only difference is, you can not change the content of the tuple unlike lists. Tuples are built-in data structures like lists.
These are useful at the times when you need to use the data structures which could not be modified at some situations..

Tuple is a immutable sequence of python objects.

Creating tuple:
                        Tuple can be created by putting comma-separated values. you can also put comma separated values between parenthesis.

Examples:
            tuple1 = ("India", "America", "France", "Russia", 2020, 1947);
            tuple2 = ( 2, 3, 5, 7, 11, 13);
            tuple3 = "a","b","c","d","e";

Empty tuple:
                      tuple = ( );


Like strings and lists tuple indices start from 0



The tuple indices can be Sliced, concatenate, and so on.


Accessing Tuple:

To access values in tuple, use square brackets for slicing along with index or indices for the values of particular index.

Example: There are two tuples  tuple1 and tuple2
                tuple1 = ("India", "America","Japan", "Germany",2020);
                tuple2 = (2,3,5,7,11,13,17);

           compute: tuple1[0] and tuple2[1:5]

Output:



Updating tuple : Tuples are immutable lists, you can not change the contents/items of any tuples.

portions of the tuple can be taken to create new tuple.

Example :  take two tuples tup1 and tup2 populated with following items
                   tup1 = (12, 24, 36, 48);
                   tup2 = ('Pre' , 'post');
now, perform
                   tup12 =  tup1  +  tup2

Output :



Deleting tuple: 

  •  Individual tuple element can not be deleted. 
  •  You can do it by creating new tuple, dropping the individual element.
  • use del keyword to delete the tuple.

Example :  take tuple1

               tuple1 = ("India", "America","Japan", "Germany",2020);
               
delete this by using
                      del  tuple1;

Output:



Tuple Operations: 


  • Length :   Length of the tuple 
                                e.g.      len (1,2,3)    will return 3
  • Concatenation:  concatenates two or more tuples
                               e.g      (1,2,4,5) + ( 6,7,8)  will result
                                            (1,2,4,5,6,7,8)
  • Repetition: Use astrisk (*) followed with number to repeat
                             e.g.      ('Hello',) * 3   will return
                                                  ('Hello','Hello','Hello')
  • Membership:    gives  TRUE if the element is a member or FALSE  if it is not the member.
                            e.g.    4 in (1,2,3,4,5)  will result TRUE 
                        while     6  in (1,2,3,4,5)  will result FALSE
  • Iteration:


Indexing and slicing 
                           Indexing and slicing works the same way as it does in strings.

                                                         you can refer to the post Lists in Python



Buil-in Tuple Functions:

  • cmp
                 compares two strings . it returns boolean value
                                 cmp (tuple1 , tuple2)
  • len
                returns the length of  tuple or items/elements in the tuple
                                 len (tuple1)
  • max
                 returns item from the tuple with maximum value. 
                                 max(tup1)
  • min

                   returns item from the tuple with minimum value. 
                                 min(tup1)
  • tuple(seq)
                      converts a list into tuple




Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mod...

Popular Posts