Bootstrap FreeKB - Python (Scripting) - Combine or merge lists
Python (Scripting) - Combine or merge lists

Updated:   |  Python (Scripting) articles

Here is how you can combine lists.

#!/usr/bin/python3

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b

print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")

 

Which should produce the following.

a = [1, 2, 3]
b = [4, 5, 6]
c = [1, 2, 3, 4, 5, 6]

 

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System). itertools can be used if you need to merge the lists, alternating between the elements in each list.

#!/usr/bin/python3
import itertools

a = [1, 2, 3]
b = [4, 5, 6]
c = list(itertools.chain.from_iterable(zip(a,b)))

print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")

 

Which should produce the following.

a = [1, 2, 3]
b = [4, 5, 6]
c = [1, 4, 2, 5, 3, 6]

 

Or like this, with three lists, alternating between the elements in each list.

#!/usr/bin/python3
import itertools

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = list(itertools.chain.from_iterable(zip(a,b,c)))

print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print(f"d = {d}")

 

Which should produce the following.

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = [1, 4, 7, 2, 5, 8, 3, 6, 9]

 

And here is how you could map the items in each list.

#!/usr/bin/python3
import itertools

a        = [1, 2, 3]
b        = [4, 5, 6]
combined = list(itertools.chain.from_iterable(zip(a,b)))
odd      = range(1, len(combined), 2)

for indice in odd:
  print(f"{combined[indice-1]} maps to {combined[indice]}")

 

Or like this.

#!/usr/bin/python3
import itertools

a        = [1, 2, 3]
b        = [4, 5, 6]
combined = list(itertools.chain.from_iterable(zip(a,b)))
even     = range(0, len(combined), 2)

for indice in even:
  print(f"{combined[indice-1]} maps to {combined[indice+1]}")

 

Which should print the following.

1 maps to 4
2 maps to 5
3 maps to 6

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8a92b7 in the box below so that we can be sure you are a human.