Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Advanced Packing and Unpacking Patterns | Packing and Unpacking in Python
Functional Programming Concepts in Python

Advanced Packing and Unpacking Patterns

Desliza para mostrar el menú

Extended unpacking in Python allows you to capture multiple elements from a sequence into a single variable using the * operator. This technique is especially useful when you want to assign the first and last elements to specific variables and collect the remaining elements in between.

Note
Note

The * operator tells Python to collect any remaining elements that have not been assigned to other variables.

123456
numbers = [1, 2, 3, 4, 5] first_val, *middle_vals, last_val = numbers print("first_val:", first_val) print("*middle_vals:", middle_vals) print("last_val:", last_val)

In this case *middle_vals captures all elements between the first and last, so middle_vals , becomes [2, 3, 4].

In the assignment:

a, *b, c = [1, 2, 3, 4, 5]

  • The variable a receives the first value;
  • c receives the last;
  • b gathers all the values in between.

This approach makes your code more flexible and expressive, especially when dealing with sequences of unknown or variable length. Extended unpacking is not limited to lists; it works with any iterable, including tuples and even strings. By mastering these patterns, you can write cleaner, more readable code that adapts easily to changes in data structure.

question mark

What does the *c variable capture in the assignment a, b, *c = [1, 2, 3, 4, 5]?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 6

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 1. Capítulo 6
some-alt