搜尋此網誌

2026年7月29日星期三

Function Structure

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.

There is no difference in slicing syntax or behavior between lists and tuples. Both are sequence types in Python, so slicing works the same way.

# List
lst = ['apple', 'banana', 'cherry']
print(lst[0:2])   # ['apple', 'banana']

# Tuple
t = ('apple', 'banana', 'cherry')
print(t[0:2])     # ('apple', 'banana')

def performOperation(*args):
    print(args)
    
performOperation(1,2,3)

The * before args means: “pack all extra positional arguments into a tuple.”
Inside the function, args is a tuple containing whatever values you passed in.

def performOperation(*args, **kwargs): print(args) print(kwargs) performOperation(1, 2, 3, operation='sum')

*args

Collects all positional arguments into a tuple.
Here: args = (1, 2, 3)

**kwargs
Collects all keyword arguments into a dictionary.
Here: kwargs = {'operation': 'sum'}

Output:
(1, 2, 3) {'operation': 'sum'}

When you pass arguments like operation='sum', Python treats operation as a keyword.
Inside the function, **kwargs collects all keyword arguments into a dictionary.

>>> my_dict = {"operation": "sum", "message": "Hello"}
... print(my_dict["operation"])  # sum
...
sum

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

沒有留言:

發佈留言