1

http://diveintopython3.ep.io/native-datatypes.html

I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far.

For example the .append() method is what I'm looking for, but it relies on the fact that the list first exists. Any suggestions?

1

2 Answers 2

4

You can create an empty list like this

L=list()

or

L=[]
Sign up to request clarification or add additional context in comments.

7 Comments

Note that the second way is more idiomatic and "Pythonic".
@music freak, I think I would agree that it is more idiomatic, but it does give up some of Python's beautiful dynamicness.
@gnibbler: How so? Both examples are functionally equal, so I don't see the difference besides readability.
@musicfreak, list does a name lookup, so I can change the behaviour by having something in my locals() or globals() called list. Not saying it's a good idea here, but that type of thing can be useful in some circumstances
@musicfreak, for example if I wanted to test a module using blist instead of list see: pypi.python.org/pypi/blist
|
1

As noted by others, you can create an empty list with the list literal operator [].

Its worth noting that you can initialise the list with values if you always need to start with a few values already in place:

a = 5
L = [42, -12, a]

Comments

Your Answer

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