How to pair elements in two lists one by one, Python

created at 07-23-2021 views: 3

Requirement

realize the pairing of the elements from two lists one by one.

Ordinary method


L1 = ['x', 'y', 'z']
L2 = [1, 2, 3]
L3 = []
for a in L1:
    for b in L2:
        L3.append((a, b))
print(L3)

output:

[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

List parse

L1 = ['x','y','z']
L2 = [1,2,3]
L3 = [ (a,b) for a in L1 for b in L2 ]
print(L3)

output

[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
created at:07-23-2021
edited at: 07-23-2021: