Python Tuples: A Complete Guide

🔥 Part-1: Tuples in Python (Complete Guide) 🔥 Tuples are one of the most important data structures in Python — simple, fast, and immutable! Let’s break it down in an easy and practical way 👇 📌 What is a Tuple? 👉 An ordered, immutable collection 👉 Allows duplicate values 👉 Written using parentheses () Example: fruits = ("apple", "orange", "cherry", "apple") print(fruits) # Output: ('apple', 'orange', 'cherry', 'apple') ✨ Ways to Create Tuples 🔹 1. Using Parentheses fruits = ("apple", "orange", "cherry") 🔹 2. Without Parentheses (Tuple Packing) numbers = 1, 2, 3, 4 print(type(numbers)) # Output: <class 'tuple'> 🔹 3. Single Element Tuple (Important ⚠️) single_tuple = ("apple",) print(type(single_tuple)) # Output: <class 'tuple'> 👉 Without comma, it becomes a string! 🎯 Accessing Elements 🔹 Indexing colors = ("red", "green", "blue", "orange") print(colors[0]) # red print(colors[-1]) # orange 🔹 Slicing nums = (10, 20, 30, 40, 50) print(nums[1:4]) # (20, 30, 40) ⚙️ Tuple Operations 🔹 Concatenation (+) print((1, 2) + (3, 4)) # (1, 2, 3, 4) 🔹 Repetition (*) print(("apple",) * 3) # ('apple', 'apple', 'apple') 🔁 Iteration in Tuple 🔹 Using for loop colors = ("red", "green", "blue") for color in colors: print(color) 🔹 Using while loop fruits = ("apple", "mango", "cherry") i = 0 while i < len(fruits): print(fruits[i]) i += 1 🛠️ Useful Methods & Functions 🔹 count() nums = (1, 2, 3, 2, 2) print(nums.count(2)) # 3 🔹 index() colors = ("red", "green", "blue") print(colors.index("green")) # 1 🔹 sorted() (returns list) nums = (3, 1, 2) print(sorted(nums)) # [1, 2, 3] 🔹 Built-in Functions numbers = (10, 20, 30, 40) print(len(numbers)) # 4 print(sum(numbers)) # 100 print(min(numbers)) # 10 print(max(numbers)) # 40 🎁 Packing & Unpacking 🔹 Unpacking coordinates = (10, 20, 30) x, y, z = coordinates print(y) # 20 🔹 Packing a = "Madhav" b = 21 c = "Engineer" tuple_pack = (a, b, c) print(tuple_pack) # ('Madhav', 21, 'Engineer') 🚀 Key Takeaways ✔ Tuples are immutable (cannot change) ✔ Faster than lists ✔ Useful for fixed data & security ✔ Supports indexing, slicing & iteration 💬 Stay tuned for Part-2 (Advanced Tuple Concepts) #Python #PythonProgramming #DataStructures #CodingTutorial #DataScience #SoftwareDevelopment

To view or add a comment, sign in

Explore content categories