Python append lists into lists

Question:

I am trying to write a function that goes through a matrix. When a criteria is met, it remembers the location.

I start with an empty list:

locations = []

As the function goes through the rows, I append the coordinates using:

locations.append(x)
locations.append(y)

At the end of the function the list looks like so:

locations = [xyxyxyxyxyxy]

My question is:

Using append, is it possible to make the list so it follows this format:

locations = [[[xy][xy][xy]][[xy][xy][xy]]]

where the first bracket symbolizes the locations of a row in the matrix and each location is in it’s own bracket within the row?

In this example the first bracket is the first row with a total of 3 coordinates, then a second bracket symbolizing the 2nd row with another 3 coordinates.

Asked By: DGDD

||

Answers:

Try this:

locations = [[]]
row = locations[0]
row.append([x, y])
Answered By: Mark Ransom

Instead of

locations.append(x)

You can do

locations.append([x])

This will append a list containing x.

So to do what you want build up the list you want to add, then append that list (rather than just appending the values). Something like:

 ##Some loop to go through rows
    row = []
    ##Some loop structure
        row.append([x,y])
    locations.append(row)
Answered By: hankd

Try something like:

def f(n_rows, n_cols):
    locations = [] # Empty list
    for row in range(n_rows):
        locations.append([]) # 'Create' new row
        for col in range(n_cols):
            locations[row].append([x, y])
    return locations

Test

n_rows = 3
n_cols = 3
locations = f(n_rows, n_cols)
for e in locations:
    print
    print e

>>> 

[[0, 0], [0, 1], [0, 2]]

[[1, 0], [1, 1], [1, 2]]

[[2, 0], [2, 1], [2, 2]]
Answered By: Christian Tapia

simple example

locations = []

for x in range(3):
    row = []
    for y in range(3):
        row.append([x,y])
    locations.append(row)

print locations

result:

[[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]
Answered By: furas

If you don’t go through a matrix and just want to embed some lists on a list:

groupA = [1,2,3]
groupB = ['a','b','c']
pair = []
for x in range(3):
    pair.append([groupA[x],groupB[x]])

>>>:
[[1, 'a'], [2, 'b'], [3, 'c']]
Answered By: Camilo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.