0

I am trying to create some lists from other lists putting some conditions along the way. I want to write these lists finally into a csv. Here is the code which I attempted.

x = [None]*1000
y = [None]*1000
z = [None]*1000
i = 0 
for d in range(0,len(productID)):
    for j in range(0,len(productID[d])):
        if productID[d][j].startswith(u'sku'):

            x[i] = map[productID[d][j]]
            y[i] = name[d]
            z[i] = priceID[d][productID[d][j]].get(u'e')

            i = i + 1  

plan_name = x[0:i]
dev_name  = y[0:i]
dev_price = z[0:i]

This is working fine, but I assume there should be a better way of doing this. Can anyone suggest how can I create a list while looping without having to define it first?

1
  • 3
    Have a list of tuples or dictionaries instead of three different lists. Commented Feb 3, 2013 at 15:17

1 Answer 1

3

You use .append() to add items to an initially empty list instead.

x, y, z = [], [], []
for d, sublist in enumerate(productID):
    for entry in sublist:
        if entry.startswith(u'sku'):
            x.append(map[entry])
            y.append(name[d])
            z.append(priceID[d][entry].get(u'e'))

Note that python can loop over sequences directly, and you usually do not need indexes at all. I've used the enumerate() function to add indexes to the outer loop instead (because you seem to need to index into name and priceID there).

.append() adds items to the end of the list:

>>> foo = []
>>> foo.append('bar')
>>> foo.append('spam')
>>> foo
['bar', 'spam']

You may want to read over the Python tutorial; it explains how python lists work nicely.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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