Python append lists into lists

22,612

Solution 1

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)

Solution 2

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]]]

Solution 3

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]]

Solution 4

Try this:

locations = [[]]
row = locations[0]
row.append([x, y])
Share:
22,612
DGDD
Author by

DGDD

Updated on July 10, 2022

Comments

  • DGDD
    DGDD almost 2 years

    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.

    • Rohit
      Rohit over 10 years
      I did not downvote, but you might be missing a few commas.
  • DGDD
    DGDD over 10 years
    I found this to be the easiest solution. Thanks for you help!
  • DGDD
    DGDD over 10 years
    Thanks for your help!