pythonlistraspbian

Creating an empty nested list in python


i'm trying to create an empty nested list in python. I have searched for information regarding nested list and most are usually nested lists that already has values in it.

The reason I needed a nested list is because I have a set of items: Apple, Pears and Oranges. However, Each item has another list that consists of: ID, price, quantity.

So what I'm planning is to: 1. Put all items into index 0,1,2 respectively. So, apple = [0], pears =[1], oranges =[2] 2. Create another nested list to put ID,price and quantity. So using apple as an example, I would do: apple[0][0].append(ID), apple[0][1].append(price), apple[0][2].append(quantity)

Is it possible for nested list to work these way? Or is there any other way to create an empty nested list? By the way, the apple, pears and orange all have their own python code file, so I have to import the pears and orange python file into the apple python file. I would appreciate any help given. Thank You.

Codes from apple.py:

fruits = [],[]

fruits[0],[0].append("ID")
fruits[0],[1].append("price")
fruits[0],[2].append("quantity")

Codes from pears.py:

fruits = [],[]

fruits[1],[0].append("ID")
fruits[1],[1].append("price")
fruits[1],[2].append("quantity")

Solution

  • Yes, you can do this, however be aware that your fruits object is a tuple, not a list. This means you can't append new types of fruit to it.

    >>> fruits = [],[]
    >>> type(fruits)
    <type 'tuple'>
    
    >>> fruits.append([])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'tuple' object has no attribute 'append'
    

    Use additional square brackets to make it a list of lists:

    >>> fruits = [[],[]]
    >>> type(fruits)
    <type 'list'>
    >>> fruits.append([])
    >>> fruits
    [[], [], []]
    

    Then you can populate the inner lists as you expect, only you need to omit that extra index and comma, which were not valid Python:

    >>> fruits[0].append("ID")
    >>> fruits[0].append("price")
    >>> fruits[0].append("quantity")
    >>> fruits
    [['ID', 'price', 'quantity'], [], []]
    

    And then you would repeat with fruit[1], fruit[2].

    Or you can do them all in a loop:

    fruits = []
    for n in range(3):
        fruits[n].append("ID")
        fruits[n].append("price")
        fruits[n].append("quantity")
    

    But really, this sounds like something you should be using a dict for:

    fruits = {}
    for id, fruit in enumerate(["apples", "pears", "oranges"]):
        fruits[fruit] = { "ID": id, "price": None, "quantity": 0 }
    

    Then you can use them like this:

    fruits["apples"]["price"] = 2.99
    fruits["apples"]["quantity"] = 5