-1
test = [[None for e in range(1)] for e in range(len(foobar)/2)]
for delete in range(0,len(test)):
        del test[delete][0]

This is not the most pythonic way to create an empty list

would you suggest something else?

I know that this question explains it. but this is not a duplicate of the previous one as you can see.

3
  • What's wrong with just test = [] ? Commented Aug 13, 2013 at 12:35
  • I think @pistal wants a list of empty lists. Commented Aug 13, 2013 at 12:35
  • @Brionius: yes, exactly. Commented Aug 13, 2013 at 12:36

4 Answers 4

7

Does this do what you want?

test = [[] for e in range(len(foobar)/2)]

It has the same output as your code

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

3 Comments

@pistal: This would create a list containing ten references to the same list object. If you added anything to any of the ten lists, it appears to be added to all of them, since they are all the same object.
Doesn't the question <stackoverflow.com/questions/10712002/…> contradict that or maybe i am wrong. It says you can create lists that way.
@pistal Also []*10 concatenates an empty list with itself 10 times, which results in...an empty list. [[]]*10 is a little closer, but it has the problem that @SvenMarnach describes.
0
test = [[None for e in range(1)] for e in range(len(foobar)/2)]

can be simplified to:

test = [[] for i in xrange(len(foobar)/2)]

Also don't forget to use xrange instead of range, as it returns a generator and not a complete list

4 Comments

Also, FYI, I recently learned this from a SO comment, so I'll pass it along, that range returns a generator object starting in python 3.
Yeah, but how shall i know he's not using python 3.3?
Oh, you wouldn't, and it's not a criticism, just a note.
And I meant iterator, not generator.
0

An empty list:

test = []

Unless we're missing something ;-)

Or you want an list of empty lists of a given length?

n = 100
test = [ [] for i in range(0,n) ]

Comments

0
test = map(lambda x: [], foobar[:len(foobar)/2])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.