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?
You use
.append()to add items to an initially empty list instead.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 intonameandpriceIDthere)..append()adds items to the end of the list:You may want to read over the Python tutorial; it explains how python lists work nicely.