Reputation: 1333
I need to create a list which contains two lists. Something like
biglist = [list1,list2]
with
list1 = [1,2,3]
list2 = [4,5,6,7,8]
where list1
and list2
have DIFFERENT length and are imported from file.
I did it the following way:
biglist = []
list1 = #...taken from file. I checked this and it poduces a list exactly how I want it to be: [1,2,3]
biglist.append(list1)
and likewise for list2
but the problem is that I get
biglist = [array([1,2,3]),array([4,5,6,7,8])]
as opposed to
biglist = [[1,2,3],[4,5,6,7,8]]
and I really don't want the array
thing, I prefer to have simple lists.
how to get around this?
Upvotes: 3
Views: 16246
Reputation: 16224
Just convert your list1
and list2
(those are confusing names indeed because those are numpy arrays, just a comment) with numpy.ndarray.tolist()
method and that's it
biglist = [list1.tolist(), list2.tolist()]
Upvotes: 3
Reputation: 798
There are potential two ways to approach this:
Native Function: list(object)
biglist = [list(list1), list(list2)]
Numpy Function: numpy.ndarray.tolist()
bigList = [list1.tolist(), list2.tolist()]
While the question doesn't ask for an optimal method, but here are additional 2 cents to evaluate the two potential approach. Here, we can design test cases to evaluate the performance of each approach.
import timeit
def test1():
bigList = [list(list1), list(list2)]
def test2():
bigList = [list1.tolist(), list2.tolist()]
timeit.timeit(stmt=t1, number=1000)
timeit.timeit(stmt=t2, number=1000)
The output of timeit
operation:
>>> timeit.timeit(stmt=t1, number=1000)
0.0024030208587646484
>>> timeit.timeit(stmt=t2, number=1000)
0.0007460117340087891``
Upvotes: 0
Reputation: 1734
To create a list with all elements: new_list = list1 + list2
To create a list with two lists inside: new_list = [list1, list2]
I think you want the second solution. Notice that a list can contain other datatypes inside. A list can contain ["string", 10, ["another", "list"], a_variable, more_stuff]
so creating a new list with more lists inside is easy. Just put each of your desired objects as an item.
Update: I don't know if this would work (never used numpy before) but is worth to try:
new_list = [list(str(list1)[6:-1]), list(str(list2)[6:-1])]
Upvotes: 1
Reputation: 1709
it seems your biglist
is a list of numpy array
. So,
convert numpy array
to list
by this way getting your desired output.
np.array(list_name).tolist()
new_biglist = []
for ls in biglist:
new_biglist.append(ls.tolist())
Upvotes: 0
Reputation: 2645
please try:
biglist.append(list(list1))
biglist.append(list(list2))
or if they are numpy arrays
biglist.append(list1.tolist())
biglist.append(list2.tolist())
Upvotes: 4