Python 3 indexer and sequence unpacking (unpacking substitution)

In Python 3, indexers and sequence unpacking (unpacking substitution) are used to divide tuple and list. ) Can be used in two ways. The latter is the customary underscore _ to discard variables ( _ reuse) and asterisk * to assign to the list of remaining iterable elements. /ja/3/reference/simple_stmts.html#assignment-statements) is possible.

In addition to unpacking to tuples in the Python 3 documentation, converting to a list is also considered unpacking if some of the elements on the left side can be used as variables in the code.

[a, b] = 0, 1
#The above formula is a tuple-to-list conversion, but list element b can be used as a variable.
print(b)  # 1
b = 2
print(b)  # 2
print((a, b))  # (0, 2)

Prerequisites

Types that can and cannot use indexers

The types that can be used by the indexer are classes that have __index__ abstract methods, and the types that cannot be used are those that do not have __index__. The former has types where indexes are meaningful, such as tuple and list, and the latter are types where indexes are meaningless, such as set and frozenset. Using an indexer for the latter will result in a TypeError error.

tuple1 = (0, 1, 2)
t0 = tuple1[0]
print(0)  # 0
t0, t1, t2 = tuple1
print((t0, t1, t2))  # (0, 1, 2)

set1 = {0, 1, 2}
# s0 = set1[0]  # TypeError 'set' object is not subscriptable
# print(s0)
s0, s1, s2 = set1
print((s0, s1, s2))  # (0, 1, 2)

Types with __index__ are defined as typing.SupportsIndex.

Types that can and cannot use sequence unpacking (unpacking substitution)

Types that can be unpacked in a sequence correspond to sequence. This is a type that has __getitem__ special methods and __len__ special methods, and many types such as tuple, list, and set are applicable.

Types that can and cannot use indexers and sequence unpacks

Types that can be used for both indexers and sequence unpacking are those with __index__, __getitem__, and __len__. tuple and list fall into this category, but set and frozen set do not.

Splitting tuple

Since the preceding and following (, ) can be omitted, the left side of the equal sign (unpacking destination) can be written separately and substituted.

Indexer


t = ("a", "b", "c")
a = t[0]
b = t[1]
c = t[2]
print((a, b, c))  # ('a', 'b', 'c')

tuple → tuple unpack


# tuple→tuple
a, b, c = "a", "b", "c"
print((a, b, c))  # ('a', 'b', 'c')

# tuple→tuple
a, b, c = ("a", "b", "c")
print((a, b, c))  # ('a', 'b', 'c')

# tuple→tuple
(a, b, c) = ("a", "b", "c")
print((a, b, c))  # ('a', 'b', 'c')

#Omission of unnecessary variables
(_, b, _) = ("a", "b", "c")
print((_, b, _))  # ('c', 'b', 'c')

#Put the rest into a list
(a, *bc, _, e) = ("a", "b", "c", "d", "e")
print((a, bc, _, e))  # ('a', ['b', 'c'], 'd', 'e')

tuple → list unpack


# tuple→list
[a, b, c] = ("a", "b", "c")
print((a, b, c))  # ('a', 'b', 'c')

#Omission of unnecessary variables
[_, b, _] = ("a", "b", "c")
print((_, b, _))  # ('c', 'b', 'c')

#Put the rest into a list
[a, *bc, _, e] = ("a", "b", "c", "d", "e")
print((a, bc, _, e))  # ('a', ['b', 'c'], 'd', 'e')

Splitting list

It can be treated basically like tuple. However, the preceding and following [, ] cannot be omitted.

Indexer


t = ["a", "b", "c"]
a = t[0]
b = t[1]
c = t[2]
print((a, b, c))  # ('a', 'b', 'c')

list → tuple unpack


# list→tuple
a, b, c = ["a", "b", "c"]
print((a, b, c))  # ('a', 'b', 'c')

# list→tuple
(a, b, c) = ["a", "b", "c"]
print((a, b, c))  # ('a', 'b', 'c')

#Omission of unnecessary variables
(_, b, _) = ["a", "b", "c"]
print((_, b, _))  # ('c', 'b', 'c')

#Put the rest into a list
(a, *bc, _, e) = ["a", "b", "c", "d", "e"]
print((a, bc, _, e))  # ('a', ['b', 'c'], 'd', 'e')

list → list unpacking


# list→list
[a, b, c] = ["a", "b", "c"]
print((a, b, c))  # ('a', 'b', 'c')

#Omission of unnecessary variables
[_, b, _] = ["a", "b", "c"]
print((_, b, _))  # ('c', 'b', 'c')

#Put the rest into a list
[a, *bc, _, e] = ["a", "b", "c", "d", "e"]
print((a, bc, _, e))  # ('a', ['b', 'c'], 'd', 'e')

Splitting set

Indexers are not supported. When unpacking into tuples or lists, the order is not guaranteed.

unpack of set


# set→tuple
#The order is not guaranteed.
a, b, c = {"a", "b", "c"}
print((a, b, c))  # ('a', 'b', 'c')Any of the sorts of

# set→list
#The order is not guaranteed.
[a, b, c] = {"a", "b", "c"}
print((a, b, c))  # ('a', 'b', 'c')Any of the sorts of

#set → set (cannot)
# {a, b, c} = {"a", "b", "c"}
# print((a, b, c))  # ('a', 'c', 'b')

Example

-Application of Python 3 vars

Recommended Posts

Python 3 indexer and sequence unpacking (unpacking substitution)
Python> tuple> tuple unpacking
Python and numpy tips
[Python] pip and wheel
Fibonacci sequence using Python
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
Ruby, Python and map
Python and Ruby split
Python3, venv and Ansible
Python asyncio and ContextVar
Memoization recursion and dynamic programming known by Python Fibonacci sequence
Programming with Python and Tkinter
Encryption and decryption with Python
Python: Class and instance variables
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python real division (/) and integer division (//)
Install Python and Flask (Windows 10)
About python objects and classes
About Python variables and objects
[Python] Use a string sequence
Apache mod_auth_tkt and Python AuthTkt
Å (Ongustromu) and NFC @ Python
Understand Python packages and modules
# 2 [python3] Separation and comment out
I compared Java and Python!
Python shallow and deep copy
About Python, len () and randint ()
About Python datetime and timezone
Install Python 3.7 and Django 3.0 (CentOS)
Python environment construction and TensorFlow
Python class variables and instance variables
Ruby and Python syntax ~ branch ~
[Python] Python and security-① What is Python?
Stack and Queue in Python
python metaclass and sqlalchemy declareative
Fibonacci and prime implementations (python)
Python basics: conditions and iterations
Python bitwise operator and OR
Python debug and test module
Python list and tuples and commas
Python variables and object IDs
Python list comprehensions and generators
About Python and regular expressions
python with pyenv and venv
Unittest and CI in Python
Maxout description and implementation (Python)
[python] Get quotient and remainder
Python 3 sorted and comparison functions
[Python] Depth-first search and breadth-first search
Identity and equivalence Python is and ==
Source installation and installation of Python
Python or and and operator trap
Challenge Python3 and Selenium Webdriver
About Python and os operations
Python higher-order functions and comprehensions