0
0
PythonHow-ToBeginner · 3 min read

How to Use * to Capture Remaining Elements in Python

In Python, you can use * to capture remaining elements when unpacking lists or tuples, or to collect extra positional arguments in functions. It groups all leftover items into a list, making it easy to handle variable-length data.
📐

Syntax

The * operator is used in unpacking assignments and function definitions to capture remaining elements.

  • Unpacking: first, *rest = [1, 2, 3, 4] assigns 1 to first and [2, 3, 4] to rest.
  • Function arguments: def func(a, *args): captures extra positional arguments in args as a tuple.
python
first, *rest = [1, 2, 3, 4]

def func(a, *args):
    print(a)
    print(args)
💻

Example

This example shows how * captures remaining elements when unpacking a list and when used in a function to accept extra arguments.

python
numbers = [10, 20, 30, 40, 50]
first, *middle, last = numbers
print("First:", first)
print("Middle:", middle)
print("Last:", last)

def greet(greeting, *names):
    print(greeting)
    for name in names:
        print("Hello", name)

greet("Hi", "Alice", "Bob", "Charlie")
Output
First: 10 Middle: [20, 30, 40] Last: 50 Hi Hello Alice Hello Bob Hello Charlie
⚠️

Common Pitfalls

Common mistakes include:

  • Using * without a variable name (e.g., first, * = [1, 2, 3]) which is a syntax error.
  • Expecting * to capture elements as a tuple in unpacking; it always creates a list.
  • Confusing *args (positional arguments) with **kwargs (keyword arguments) in functions.
python
try:
    exec('first, * = [1, 2, 3]')
except SyntaxError:
    print("SyntaxError: * must be followed by a variable name")

first, *rest = (1, 2, 3)
print(type(rest))  # Output: <class 'list'>
Output
SyntaxError: * must be followed by a variable name <class 'list'>
📊

Quick Reference

Summary of * usage to capture remaining elements:

Use CaseDescriptionExample
List/Tuple UnpackingCapture leftover items as a lista, *b = [1, 2, 3]
Function ArgumentsCapture extra positional args as a tupledef f(x, *args):
In Function CallsUnpack a list/tuple into argumentsf(*[1, 2, 3])

Key Takeaways

Use *var to capture remaining elements as a list during unpacking.
In functions, *args collects extra positional arguments as a tuple.
The * operator must always be followed by a variable name.
Unpacking with * helps handle variable-length data cleanly.
Remember *args differs from **kwargs which captures keyword arguments.