Output of Python Program | Set 10 (Tuples)
×


Output of Python Program | Set 10 (Tuples)

191

Output of Python Program | Set 10 (Tuples)

Tuples are immutable sequences in Python, meaning once created, you cannot modify them. They are efficient and useful for storing fixed collections of items. In this blog, we'll explore tuple operations and outputs through examples, followed by practice problems to help you master tuple handling.

Tuple Basics

Tuples are created using parentheses and support indexing, slicing, and concatenation:

tpl = (10, 20, 30, 40)
print(tpl[1])        # 20
print(tpl[-1])       # 40
print(tpl[1:3])      # (20, 30)
print(tpl + (50, 60))# (10,20,30,40,50,60)

This demonstrates accessing elements, slicing, and merging tuples.

Tuple Unpacking

Unpacking allows you to assign tuple elements to variables effortlessly:

a, b, c = (1, 2, 3)
print(a, b, c)       # 1 2 3

# Extended unpacking:
first, *middle, last = (5, 6, 7, 8, 9)
print(first, middle, last) # 5 [6,7,8] 9

Practice Problems

  1. Swap two variables using tuple unpacking.
    a = 5
    b = 10
    # your code here
    print(a, b)  # Output should be: 10 5

    Solution

    a, b = b, a
    print(a, b)  # 10 5
  2. Count occurrences of an element in a tuple.
    tpl = ('a', 'b', 'a', 'c', 'a', 'b')
    # your code here
    # Expected output: 3

    Solution

    count_a = tpl.count('a')
    print(count_a)  # 3
  3. Unpack and skip middle elements.
    tpl = (100, 200, 300, 400, 500)
    # your code here
    # Expected: print(first, last) outputs: 100 500

    Solution

    first, *_, last = tpl
    print(first, last)  # 100 500

Learn More on Tuples

Explore detailed explanations on CodingTag – Python Tuples.

Conclusion

Tuples provide a convenient and reliable way to store fixed collections of items in Python. With immutability and unpacking, they support clean and readable code patterns. Practice these problems and explore tuple functions to enhance your Python toolkit.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat