Tuple Short Questions


Q.1: What is a Tuple in Python?

  • A tuple is a built-in data type in Python used to store a collection of items.
  • Ordered: Elements have a defined order.
  • Immutable: Cannot add, remove, or change elements after creation.
  • Allows duplicates: Can store repeated values.
  • Heterogeneous: Can store elements of different data types.

Example:

my_tuple = (10, 20, 30)
print(my_tuple[0])  # Output: 10

Why use tuples?

  • Faster than lists.
  • Used for fixed collections (e.g., coordinates, settings).
  • Can be used as dictionary keys (if elements are immutable).
  • Help ensure data integrity (unchanged data).

Q.2: What is Indexing?

  • Indexing = Accessing elements by their position (index).
  • Index starts from 0.

Example:

my_list = [10, 20, 30, 40]
print(my_list[0])  # Output: 10
print(my_list[2])  # Output: 30

Q.3: What is Slicing?

  • Extracting a portion (subsequence) of a list, tuple, or string.
  • Syntax: sequence[start : stop : step]

Examples:

my_list = [10, 20, 30, 40, 50, 60]
print(my_list[1:4])   # [20, 30, 40]
print(my_list[:3])    # [10, 20, 30]
print(my_list[3:])    # [40, 50, 60]
print(my_list[::2])   # [10, 30, 50]
print(my_list[::-1])  # [60, 50, 40, 30, 20, 10]

Q.4: Indexing and Slicing with Negative Indices

  • Negative indices start from -1 (last element), -2 (second last), etc.

Example:

my_list = [10, 20, 30, 40, 50]
print(my_list[-1])   # 50
print(my_list[-2])   # 40
print(my_list[-4:-1])  # [20, 30, 40]
print(my_list[-3:])    # [30, 40, 50]
print(my_list[::-1])   # [50, 40, 30, 20, 10]


Leave a Reply

Your email address will not be published. Required fields are marked *