Python built-in functions ~ Zip ~

Introduction

In this article, I'd like to talk about the Python built-in function "zip function". I've known the existence of the "zip function" before, and I've been using it for some reason, so I'd like to deepen my understanding of the "zip function" in this period.

What is a zip function?

What is a "zip function" in the first place? Simply put, it is a collection of multiple lists given as arguments. If you want to know more, please click here. Python standard library

Basic usage

As a basic usage, the one used in the for statement can be mentioned.

#Create a list of names and ages
names = ['sato', 'suzuki', 'ito']
ages = [23, 21, 25]

for name, age in zip(names, ages):
    print('name:{},age:{}'.format(name, age))

#name:sato,age:23
#name:suzuki,age:21
#name:ito,age:25

You can put the two lists together in this way.

It is also possible with three lists.

#Create a list of names, ages and hometowns
names = ['sato', 'suzuki', 'ito']
ages = [23, 21, 25]
birthplaces = ['Tokyo', 'Aichi prefecture', 'Hokkaido']

for name, age, birthplace in zip(names, ages, birthplaces):
    print('name:{},age:{},Birthplace:{}'.format(name, age, birthplace))

#name:sato,age:23,Birthplace:Tokyo
#name:suzuki,age:21,Birthplace:Aichi prefecture
#name:ito,age:25,Birthplace:Hokkaido

You will find it useful when you want to put together a list.

You can make it even shorter if you just put it together.

list(zip(names, ages))
#[('sato', '23'), ('suzuki', '21'), ('ito', '25')]

This will return it as a tuple.

unzip

How can I get the zip back together? The answer can be given by adding "*" to the argument.

zips = list(zip(names, ages))
names2, ages2 = zip(*zips)
print(names2)
#('sato', 'suzuki', 'ito')
print(ages2)
#(23, 21, 25)

It will be returned as a tuple like this. If you want to output as a list, enclose it in "list ()".

zips = list(zip(names, ages))
names2, ages2 = list(zip(*zips))
print(names2)
#[('sato', 'suzuki', 'ito')]
print(ages2)
#[(23, 21, 25)]

When the list length is different

Let's see what happens when the list lengths are different.

#Create a list of names and ages
names = ['sato', 'suzuki', 'ito', 'kato', 'saitou']
ages = [23, 21, 25]

for name, age in zip(names, ages):
    print('name:{},age:{}'.format(name, age))

#name:sato,age:23
#name:suzuki,age:21
#name:ito,age:25

If you look at this, you can see that it is suitable for the shorter one.

Fill in the values when the list lengths are different

Earlier, when the length of the list was different, I think I was able to confirm that it fits the shorter one. So how do you fit the longer one? You can do that by using the "zip_longest module". Please see here for details. zip_longest module

Let's see.

#Create a list of names and ages
names = ['sato', 'suzuki', 'ito', 'kato', 'saitou']
ages = [23, 21, 25]

for name, age in zip_longest(names, ages):
    print('name:{},age:{}'.format(name, age))

#name:sato,age:23
#name:suzuki,age:21
#name:ito,age:25
#name:kato,age:None
#name:saitou,age:None

You can see that it is filled with "None" like this. "None" is dull, so let's enter the average age instead.

#zip_Import longest
from itertools import zip_longest

#Create a list of names and ages
names = ['sato', 'suzuki', 'ito', 'kato', 'saitou']
ages = [23, 21, 25]

#Calculate average age
age_mean = sum(ages) // len(ages)

#Specify the value to be filled with fillvalue
for name, age in zip_longest(names, ages, fillvalue=age_mean):
    print('name:{},age:{}'.format(name, age))

#name:sato,age:23
#name:suzuki,age:21
#name:ito,age:25
#name:kato,age:23
#name:saitou,age:23

You can see that it is filled with the average age.

Finally, let's check when the lengths of three or more lists are different.

#zip_Import longest
from itertools import zip_longest

#Create a list of names, ages and hometowns
names = ['sato', 'suzuki', 'ito']
ages = [23, 21, 25]
birthplaces = ['Tokyo', 'Aichi prefecture', 'Hokkaido', 'Yamanashi Prefecture']

#Calculate average age
age_mean = sum(ages) // len(ages)

#Specify the value to be filled with fillvalue
for name, age, birthplace in zip_longest(names, ages, birthplaces, fillvalue=age_mean):
    print('name:{},age:{},Birthplace:{}'.format(name, age, birthplace))

#name:sato,age:23,Birthplace:Tokyo
#name:suzuki,age:21,Birthplace:Aichi prefecture
#name:ito,age:25,Birthplace:Hokkaido
#name:kato,age:23,Birthplace:Yamanashi Prefecture
#name:saitou,age:23,Birthplace:23

When you check the output result, the birthplace of the last line is "23". Please note that you can only fill one value in this way.

Please refer to this article for countermeasures in that case. How to use Python and zip functions: Get multiple list elements at once

Finally

This time, I covered the "zip function". We look forward to helping you. We will continue to publish articles about functions and modules, so please take a look if you like.

Recommended Posts

Python built-in functions ~ Zip ~
Wrap Python built-in functions
Built-in python
Python functions
Built-in functions
python zip
Python built-in object
#Python basics (functions)
[Beginner] Python functions
Python Easy-to-use functions
Python basics: functions
Python's built-in functions
Conquer 69 Python built-in functions 6th p ~ r
Correspondence between Python built-in functions and Rust
Zip, unzip with python
Python Beginner's Guide (Functions)
Python basic course (12 functions)
[Python] Memo about functions
Useful Python built-in functions that you use occasionally
Curry arbitrary functions with Python ....
Python> lambda> tiny functions / callback functions
Getting Started with Python Functions
Python3 programming functions personal summary
Various Python built-in string operations
Study from Python Hour3: Functions
Overriding library functions in Python
Keyword arguments for Python functions
Python for super beginners Python #functions 1
Paiza Python Primer 7: Understanding Functions
Python 3 sorted and comparison functions
Python functions learned in chemoinformatics
Python higher-order functions and comprehensions
Python control syntax, functions (Python learning memo ②)
Azure Functions: Try Durable Functions for Python
[python] Manage functions in a list
Python
Recursively unzip zip files with python
About python dict and sorted functions
"Effective Python 2nd Edition" Chapter 3 <Functions>
Examine built-in functions (standard built-in functions) from globals
Using global variables in python functions
zip
Dynamically define functions (methods) in Python
How to use python zip function
Python3> Functions> Function Renaming Mechanism> f = fib
[Python3] Dynamically define global variables in functions
Build an environment for Blender built-in Python
[Introduction to Udemy Python3 + Application] 55. In-function functions
Easily use your own functions in Python
OR the List in Python (zip function)
[Control engineering] Graphing transfer functions using Python
Try using Python with Google Cloud Functions
[Introduction to Udemy Python3 + Application] 46. Zip function
Summary of built-in methods in Python list
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Use C ++ functions from python with pybind11
Use Python and MeCab with Azure Functions