tags:

views:

263

answers:

4

I am a beginner in python. I want to Create new List object in python.

My Code:

recordList=[]

mappedDictionay={}

sectionGroupName= None

for record in recordCols:
    item = record
    print item

    if not sectionGroupName == record[0]:
        sectionGroupName = record[0]
        del recordList[0:] # Here I want to create new list object for recordList
        recordList.append(item)
        mappedDictionay[sectionGroupName] = recordList
    else:
        recordList.append(tempItem)
+3  A: 

It's not that easy to understand your question, especially since your code lost its formatting, but you can create new list objects quite easily. The following assigns a new list object to the variable recordList:

recordList = list()

You could also use

recordList = []

[] and list() are equivalent in this case.

Epcylon
Thanks for the information. It is very useful for me.
+3  A: 

Python is garbage-collected. Just do

recordList = []

and you'll have a new empty list.

unwind
Thanks for the information. It is very useful for me.
@crk: Feel free to accept the answer, of course. :)
unwind
+3  A: 

Don't use del. Period. It's an "advanced" thing.

from collections import defaultdict

mappedDictionay= defaultdict( list ) # mappedDictionary is a poor name
sectionGroupName= None

for record in recordCols:
    mappedDictionay[record[0]].append( record )
S.Lott
Thanks for the information. It is very useful for me.
@crk: If it's useful, perhaps you should click accept. If it's not acceptable, perhaps you should explain what more you need.
S.Lott
A: 

You can use list() or simply [] to create a new list. However, I think what you are trying to achieve can be solved simply by using grouby:

from itertools import groupby
mappedIterator = groupby(recordCols, lambda x: x[0])

or

from itertools import groupby
from operator import itemgetter
mappedIterator = groupby(recordCols, itemgetter(0))

if you prefer.

The groupBy function will return an iterator rather than a dictionary, where each item is of the form (category, sub-iterator-over-items-in-that-category).

If you really want to convert it into a dictionary like you have it in your code, you can run the following afterwards:

mappedDictionary = dict(( (x[0], list(x[1])) for x in mappedIterator ))
buge
Thanks for the information. It is very useful for me.