Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two lists to make each element of the list have two values, one from each list?

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!

like image 529
smallzZz8 Avatar asked Sep 13 '18 06:09

smallzZz8


People also ask

How do you add two lists of elements together?

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.

How do I combine two values in a list python?

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.

How do you concatenate multiple lists?

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.

How do you combine lists within a list python?

Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.


1 Answers

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']]
like image 169
Rahul K P Avatar answered Oct 07 '22 00:10

Rahul K P