Nono.MA

Combine or extend Python lists

JANUARY 20, 2023

Today I learned you can use the plus (+) operator to concatenate or extend lists in Python.

Say you have two lists.

list_a = [1, 2, 3]
list_b = ['Nono', 'MA']

And that you want to create a continuous list with the contents of both, which would look something like [1, 2, 3, 'Nono', 'MA'].

You can simple add both lists to obtain that result.

>>> combined_list = [1, 2, 3] + ['Nono', 'MA']
>>> combined_list
[1, 2, 3, 'Nono', 'MA']

Of course, it doesn't too much sense in this example because we're explicitly defining the lists and we could define a combined list directly.

combined_list = [1, 2, 3, 'Nono', 'MA']

But it can be useful when we actually need to add lists, for instance to concatenate the results of glob file listing operations.

>>> from glob import glob
>>> files_a = glob('a/*')
>>> files_a
['a/file.txt', 'a/image.jpg']
>>> files_b = glob('b/*')
>>> files_b
['b/data.json', 'b/profile.jpeg']
>>> all_files = files_a + files_b
>>> all_files
['a/file.txt', 'a/image.jpg', 'b/data.json', 'b/profile.jpeg']

CodePythonTil