14

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)
1
  • Could you show what data structure you're starting with, and what you want to end with? There's more than likely a better way to do what you want but I can't puzzle it out from your example code. Sep 24, 2009 at 9:30

6 Answers 6

20

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.

0
7

Python is garbage-collected. Just do

recordList = []

and you'll have a new empty list.

0
4

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 )
1
  • @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
    Sep 25, 2009 at 0:33
2

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 ))
0
0

You want to create a new list?
It's easy: for eg, you wanna make a list of days, write the following:

new_list=['mon','tue','wed','thurs','fri',sat','sun']

Here the name of the list is new_list and it contains the name of different week days.

Note: never forget use [ ] brackets to make a list, using ( ) will create a tuple, a very different object and { } will create a dictionary object which will raise a error instead.

0

It's easy to create a new list!
If you want it empty, then just define it like this:

NameOfList = []

or:

NameOfList = list()