Python - List of lists of different lengths
10,225
Solution 1
please try:
biglist.append(list(list1))
biglist.append(list(list2))
or if they are numpy arrays
biglist.append(list1.tolist())
biglist.append(list2.tolist())
Solution 2
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()]
Author by
johnhenry
Updated on June 14, 2022Comments
-
johnhenry almost 2 years
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
andlist2
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?-
enterML over 6 yearsIt seems that your
list1
andlist2
are numpy arrays. You can do this first:list1 = list.tolist()
list2 = list2.tolist()
and then append them to your big list -
user1767754 over 6 yearsuse extend instead of append
-
A.J. Uppal over 6 yearsPlease show the code where you parse the list from the file, because it is in that code that your list is parsed as a numpy array rather than a python list.
-
-
user1767754 over 6 yearstolist? what python version is that?
-
skrubber over 6 yearsthere's no such method for lists
-
A.J. Uppal over 6 yearsIt exists for
numpy.array
types -
skrubber over 6 years@ᴬᴶᵁᴾᴾᴬᴸ I think the asker made it clear that the two objects are lists
-
A.J. Uppal over 6 years@Mokshyam no the OP didn't. Just because the variable name has "list" in it doesn't make it a list. If you look at the latter part of the post, the lists are shown as
array([1,2,3])
. This is anumpy.array
, not a list. -
Simon Mengong over 6 years
list1
andlist2
are imported, so when he does this,biglist
has the array things that he does not want. That's the issue -
Saelyth over 6 yearsOh, I see now, that's tricky. The only fix that comes into my mind is.. I will update this answer.
-
Damian Lattenero over 6 yearsThanks for the correction, it's a good answer and it's a plus one :)
-
Damian Lattenero over 6 years@user1767754 I modified the answer, I didn't clarify that the names wasn't the best, list1 is not a list is a npArray :), thanks for comment
-
Damian Lattenero over 6 years@Mokshyam You are absolutely right, that's why I added in the edit of my answer, that I was talking about npArrays, not python list, even if the name of variables are list1, they are array, not list
-
Damian Lattenero over 6 years@ᴬᴶᵁᴾᴾᴬᴸ thanks so much for helping me clarify my answer you rules :)