Concatenate two lists element-wise in Python

PythonServer Side ProgrammingProgramming

Pyhton has great data manipulation features. In this article we will see how to combine the elements from two lists in the same order as they are present in the lists.

With zip

The zip function can take in the two lists as parameters and concatenate them. We design a for loop to capture these combinations and put them into a new list.

Example

Live Demo

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use zip
res = [i + j for i, j in zip(listA, listB)]
# Result
print("The concatenated lists: ",res)

Output

Running the above code gives us the following result −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']

With lambda and map

The map function will apply the same function again and again to the parameters passed onto it. We will also use a lambda function to combine the individual elements one by one from the two lists through zip.

Example

Live Demo

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use map
res = list(map(lambda(i, j): i + j, zip(listA, listB)))
# Result
print("The concatenated lists: ",res)

Output

Running the above code gives us the following result −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']
{"ft_lang_label":"__label__en","ft_lang_prob":0.6872684,"math_prob":0.54140663,"size":1450,"snap":"2022-05-2022-21","text_gpt3_token_len":386,"char_repetition_ratio":0.15214385,"word_repetition_ratio":0.42918456,"special_character_ratio":0.30068967,"punctuation_ratio":0.17123288,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9649219,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-01-21T07:47:24Z\",\"WARC-Record-ID\":\"<urn:uuid:f6617ad1-3e57-4eef-9502-d968d45f5eb8>\",\"Content-Length\":\"32355\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:334311f9-ad75-4461-b144-35eee80d4a07>\",\"WARC-Concurrent-To\":\"<urn:uuid:713f524f-09ef-4ee3-9c02-a6e096f41d74>\",\"WARC-IP-Address\":\"192.229.210.176\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/concatenate-two-lists-element-wise-in-python\",\"WARC-Payload-Digest\":\"sha1:RFX6K7ITS5RYZTLSORVDY3QH32EGTZA6\",\"WARC-Block-Digest\":\"sha1:FQ3YJTHVWAWO7XT7MHFDQ3SAK6QRO3VL\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-05/CC-MAIN-2022-05_segments_1642320302740.94_warc_CC-MAIN-20220121071203-20220121101203-00007.warc.gz\"}"}