Python add two lists different length

Often you might be interested in zipping [or merging] together two lists in Python. Fortunately this is easy to do using the zip[] function.

This tutorial shows several examples of how to use this function in practice.

Example 1: Zip Two Lists of Equal Length into One List

The following syntax shows how to zip together two lists of equal length into one list:

#define list a and list b a = ['a', 'b', 'c'] b = [1, 2, 3] #zip the two lists together into one list list[zip[a, b]] [['a', 1], ['b', 2], ['c', 3]]

Example 2: Zip Two Lists of Equal Length into a Dictionary

The following syntax shows how to zip together two lists of equal length into a dictionary:

#define list of keys and list of values keys = ['a', 'b', 'c'] values = [1, 2, 3] #zip the two lists together into one dictionary dict[zip[keys, values]] {'a': 1, 'b': 2, 'c': 3}

Example 3: Zip Two Lists of Unequal Length

If your two lists have unequal length, zip[] will truncate to the length of the shortest list:

#define list a and list b a = ['a', 'b', 'c', 'd'] b = [1, 2, 3] #zip the two lists together into one list list[zip[a, b]] [['a', 1], ['b', 2], ['c', 3]]

If youd like to prevent zip[] from truncating to the length of the shortest list, you can instead use the zip_longest[] function from the itertools library.

By default, this function fills in a value of None for missing values:

from itertools import zip_longest #define list a and list b a = ['a', 'b', 'c', 'd'] b = [1, 2, 3] #zip the two lists together without truncating to length of shortest list list[zip_longest[a, b]] [['a', 1], ['b', 2], ['c', 3], ['d', None]]

However, you can use thefillvalueargument to specify a different fill value to use:

#define list a and list b a = ['a', 'b', 'c', 'd'] b = [1, 2, 3] #zip the two lists together, using fill value of '0' list[zip_longest[a, b, fillvalue=0]] [['a', 1], ['b', 2], ['c', 3], ['d', 0]]

You can find the complete documentation for the zip_longest[] function here.

Video liên quan

Chủ Đề