Python List Unpacking: A Beginner's Guide

AndreAndre
1 min read

List unpacking is a simple yet powerful feature of Python that allows you to extract the elements of an iterable and assign them to variables in a single line of code. Here's an example:

a, b, c = [1, 2, 3]
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3

You can also use this feature with other iterable types, such as strings, sets, and dictionaries. For example, you can unpack the characters of a string and assign them to variables:

string = 'Hello'
a, b, c, d, e = string
print(a) # Output: 'H'
print(b) # Output: 'e'
print(c) # Output: 'l'
print(d) # Output: 'l'
print(e) # Output: 'o'

You can also use the * operator to capture any extra elements in the list:

my_list = [1, 2, 3, 4, 5]
a, b, *c = my_list
0
Subscribe to my newsletter

Read articles from Andre directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Andre
Andre