Okay so I have two lists. I am trying to upload them to a .json file but I first want to combine them. I would like to combine the two lists making each element of the merged list 2 parts. For example
list1 = [[4],[5],[6],[7]]
list2 = [["a"],["b"],["c"],["d"]]
Then once they are combined I would like them to look like this:
mergedList = [[4, "a"], [5, "b"], [6, "c"], [7, "d"]]
How would I go about doing this? If it makes it easier, all I am trying to do is save 3 data values to this .json PER item that I am searching for. Thanks!
Method #1 : Naive Method In this method, we simply run a loop and append to the new list the summation of the both list elements at similar index till we reach end of the smaller list. This is the basic method to achieve this task.
One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.
The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation.
Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.
You can do this with list comprehension,
In [18]: [i+j for i,j in zip(list1,list2)]
Out[18]: [[4, 'a'], [5, 'b'], [6, 'c'], [7, 'd']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With