0

I need to make a list of lists out of 4 lists I have. However, I want each list to become a column instead of a row in the final list of lists.

Each of my lists is 10 items long, so I have made a an empty list of lists filled with 0s which is 4 by 10.

rows, columns = (10, 4)
biglist = [[0 for i in range(columns)] for j in range(rows)]

I now want to know how to fill the empty list of lists with my individual lists.

Or, would it be better to make 10 new lists by reading each place from each of the four lists one at a time, and then use these new lists to fill in the empty list of lists?

3
  • Note: in Python the word array is commonly associated with array variables from the numpy package. What you want can be better described as a 'list of lists' to avoid confusion. Commented Oct 1, 2019 at 3:40
  • @jberrio How can I make an array using numpy from my list of lists? Commented Oct 1, 2019 at 3:56
  • 1
    That's a different question mate. This forum works one question at a time. Just Google 'how to create numpy arrays' - there are hundreds of webpages giving very simple examples on how to do it. Commented Oct 1, 2019 at 3:58

2 Answers 2

1

If I understood you correctly, you want 10 rows and 4 columns in your final list.

Test Data Preparation:

l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = [x*10 for x in l1]
l3 = [x*100 for x in l1]
l4 = [x*1000 for x in l1]

Code you will need to write:

grid = [l1, l2, l3, l4]
trGrid = list(zip(*grid))

Testing:

for row in trGrid:
    print(row)
Sign up to request clarification or add additional context in comments.

Comments

0

(Edit) One method is to make a list of lists, and then flip it (Here we don't need the lists of zeros):

array = [[list1],[list2],[list3],[list4]]
def flipper(array):
    flipped = [[] for x in range(len(array[0]))]
    for y in range(len(array)):
        for x in range(len(array[0])):
            flipped[x].append(array[y][x])
    return flipped

Okay this is working... again assuming all list elements are the same length.

6 Comments

using this method, each of my lists is a row in the array. I want to make each list a column.
Just a random variable name. The unprocessed lists of lists. Incidentally, the numpy and pandas modules are great for arrays, much faster than this list approach.
I tried the first method you wrote in the top block of code and it did not work. Here is the output [[0, 1, 2, 3]]
how can I use numpy to transpose?
Google "how can I use numpy to transpose?" - you'll find plenty of good answers
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.