Python Tutorial - Master Python Programming For Beginners from Scratch

  • Home
  • Getting Started
  • Basics
  • OOP
  • Advanced Python
  • Tkinter
Home » Python Basics » How to Unpack a List in Python

How to Unpack a List in Python

Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise.

Introduction to the list unpacking

The following example defines a list of strings:

colors = ['red', 'blue', 'green']
Code language: Python (python)

To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:

red = colors[0] blue = colors[1] green = colors[2]
Code language: Python (python)

However, Python provides a better way to do this. It’s called sequence unpacking.

Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example:

red, blue, green = colors
Code language: Python (python)

This statement assigns the first, second, and third elements of the colors list to the red, blue, and green variables.

In this example, the number of variables on the left side is the same as the number of elements in the list on the right side.

If you use a fewer number of variables on the left side, you’ll get an error. For example:

colors = ['red', 'blue', 'green'] red, blue = colors
Code language: Python (python)

Error:

ValueError: too many values to unpack (expected 2)
Code language: Python (python)

In this case, Python could not unpack three elements to two variables.

Unpacking and packing

If you want to unpack the first few elements of a list and don’t care about the other elements, you can:

  • First, unpack the needed elements to variables.
  • Second, pack the leftover elements into a new list and assign it to another variable.

By putting the asterisk (*) in front of a variable name, you’ll pack the leftover elements into a list and assign it to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print(red) print(blue) print(other)
Code language: Python (python)

Ouptut:

red blue ['green']
Code language: Python (python)

This example assigns the first and second elements of the colors list to the red and green variables. And it assigns the last element of the list to the other variable.

Here’s another example:

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print(cyan) print(magenta) print(other)
Code language: Python (python)

Output:

cyan magenta ['yellow', 'black']
Code language: Python (python)

This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the other variable.

Summary

  • Unpacking assigns elements of the list to multiple variables.
  • Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.
  • Was this tutorial helpful ?
  • YesNo
Previous Python List Slice
Next How to Use a For Loop to Iterate over a List

Getting Started

  • What is Python
  • Install Python
  • Setup VS Code for Python
  • Develop Python Hello World Program

Python Fundamentals

  • Python Syntax
  • Variables
  • Strings
  • Numbers
  • Boolean
  • Constants
  • Comments
  • Type Conversion

Control Flow

  • if…else
  • Ternary Operator
  • for Loop
  • while Loop
  • break
  • continue
  • pass

Functions

  • Python Functions
  • Default Parameters
  • Keyword Arguments
  • Recursive Functions
  • Lambda Expressions
  • Function Docstrings

Python List

  • List
  • Tuple
  • Sorting a List in Place: sort()
  • Sorting a List: sorted()
  • Slicing a List: [::]
  • Unpacking a List
  • Iterating over a List: for loop
  • Finding Index of an Element: index()
  • Iterables
  • Transform List Elements: map()
  • Filtering List Elements: filter()
  • Reducing List Elements: reduce()
  • List Comprehensions

Python Dictionary

  • Dictionary
  • Dictionary Comprehension

Python Set

  • Set
  • Set Comprehension
  • Union of Sets
  • Intersection of Sets
  • Difference between Sets
  • Symmetric Difference of Sets
  • Subset
  • Superset
  • Disjoint Sets

Exception Handling

  • try…except
  • try…except…finally
  • try…except…else

Python Loop with Else Clause

  • for…else
  • while…else
  • do…while Emulation

More on Functions

  • Unpacking Tuples
  • The *args Parameters
  • The **kwargs Parameters
  • Partial Functions

Modules

  • Modules
  • Module Search Path
  • Python __name__
  • Packages

File I/O

  • Reading a Text File
  • Writing to a Text File
  • Creating a Text File
  • Checking If a File Exists
  • Reading from a CSV File
  • Writing to a CSV File

Managing Third-party Packages

  • Python Package Index (PyPI) & PIP
  • Python Virtual Environments
  • Install pipenv on Windows
  • Using pipenv Tool

About pythontutorial.net

Pythontutorial.net helps you master Python programming from scratch fast.

Site Links

  • Home
  • Contact
  • About
  • Privacy Policy

Recent Python Tutorials

  • Tkinter StringVar
  • Tkinter PhotoImage
  • Tkinter OptionMenu
  • Tkinter ScrolledText
  • How to Change the Appearances of Widgets Dynamically Using Ttk Style map() Method

Python References

  • Python String Methods
  • Python MySQL
  • Python PostgreSQL
  • Python Oracle
  • Python SQLite

Copyright © 2021 · by pythontutorial.net. All rights reserved. Log in