Fundamentals of Python : 4. Python Tuples

  Fundamentals of Python

 4. Python Tuples

Tuples are one of the fundamental data structures in Python. Like lists, tuples are ordered collections, but unlike lists, they are immutable—once defined, their elements cannot be modified. This immutability makes tuples ideal for fixed data collections and allows them to be used as keys in dictionaries.

Tuples can store elements of different types, including other tuples. Because they support indexing and slicing, they allow element access just like lists. Tuples are defined using parentheses ().

🔹 1. Creating a Tuple

Program:

fruits = ("apple", "mango", "banana", "pineapple")
fruits
Answer: ('apple', 'mango', 'banana', 'pineapple')

type(fruits)
Answer: <type 'tuple'>

Explanation: A tuple is created using round brackets (parentheses), and it can store multiple elements in order. The type() function confirms that the data type is tuple.

🔹 2. Getting the Length of a Tuple

Program:

len(fruits)
Answer: 4

Explanation: The len() function returns the number of items in the tuple.

🔹 3. Accessing Tuple Elements

Program:

fruits[0]
Answer: 'apple'

fruits[:2]
Answer: ('apple', 'mango')

Explanation:

  • fruits[0] accesses the first element using index 0.
  • fruits[:2] slices the tuple from index 0 to 1 (excluding index 2).

🔹 4. Combining Tuples (Tuple Concatenation)

Program:

vegetables = ('potato', 'carrot', 'onion', 'radish')
eatables = fruits + vegetables
eatables
Answer: ('apple', 'mango', 'banana', 'pineapple', 'potato', 'carrot', 'onion', 'radish')

Explanation: The + operator is used to join two tuples. This creates a new tuple that includes elements from both the original tuples.

🔹 Summary: Key Characteristics of Tuples

  • ✅ Ordered: Elements maintain their insertion order.

  • ✅ Immutable: Once created, elements cannot be changed or deleted.

  • ✅ Hashable: Tuples can be used as keys in dictionaries.

  • ✅ Flexible: Can store mixed data types and even nested tuples.

  • ✅ Efficient: Slightly faster and more memory-efficient than lists when working with fixed data.

📢 If you found this explanation helpful, don’t forget to share it, follow for more Python insights, and drop your thoughts or questions in the comments below! 🐍💡💬

Comments

Popular posts from this blog

Fundamental of python : 1.Python Numbers