A tuple in Python is one of the basic data structures, similar to a list but with some important differences.
Defined with parentheses ( )
my_tuple = (1, 2, 3)
Ordered → elements keep their position.
Immutable → once created, you cannot change, add, or remove elements.
Can contain mixed data types (numbers, strings, even other tuples).
Supports indexing and slicing like lists.
# Creating a tuple t = ('apple', 'banana', 'cherry') # Accessing elements print(t[0]) # 'apple' print(t[-1]) # 'cherry' # Slicing print(t[0:2]) # ('apple', 'banana') # Nested tuple nested = (1, (2, 3), 4) print(nested[1][0]) # 2
Negative indexing
In Python, negative indices count from the end of the sequence.
-1→ last element
Slice notation [start:stop]
start = 0→ begin at index 0 ('apple').stop = 2→ go up to index 2, but not including it.
* before args means: “pack all extra positional arguments into a tuple.”args is a tuple containing whatever values you passed in.args = (1, 2, 3)
kwargs = {'operation': 'sum'}
Output:(1, 2, 3)
{'operation': 'sum'}
operation='sum', Python treats operation as a keyword.**kwargs collects all keyword arguments into a dictionary.
import math
def performOperation(*args, operation='sum'):
if operation == 'sum':
return sum(args)
if operation == 'multiply':
return math.prod(args)
performOperation(1,2,3,6,7,8, operation='sum')
Function Definition
*args → packs all positional arguments into a tuple.
Here: args = (1, 2, 3, 6, 7, 8)
operation='sum' → keyword argument with default value 'sum'.
print(performOperation(1,2,3,6,7,8, operation='multiply'))
Uses math.prod(args) → multiplies all values.math.prod stands for “product” — it multiplies all the numbers in an iterable together.
Microsoft Copilot