FeMaiden
FeMaiden

Reputation: 121

Difference between foo=list, foo=[], and foo=list()?

I'm new to python (but not programming in general) and don't really understand what is going on with lists. I have thousands of test sets in a text file and each test set is 256 (could be dfferent) x,y points. What I want to do is store each point in a test set to a list and then store each list in another list, effectively creating a 2D list. Two of the three options I've tried are error free but I don't know what the different options mean or why I should pick one over another. This is not the same as "Least Astonishment" and the Mutable Default Argument because that doesn't explain which of these is a list and what the other definitions are.

foo= list
foo.append(1)#TypeError: descriptor 'append' requires a 'list' object but received a 'int'

bar= []
bar.append(1)#no error

baz= list()
baz.append(1)#no error

Upvotes: 0

Views: 803

Answers (3)

Kyle Willmon
Kyle Willmon

Reputation: 709

This is because foo = list makes foo an alias for the list type. No actual list object has been instantiated in that line. However, if you have a list object, you can use list.append() (or foo.append()) in order to append to it.

Like so:

foo = list
bar = [1]

list.append(bar, 2)
# bar is now [1, 2]

foo.append(bar, 3)
# bar is now [1, 2, 3]

Since your example code calls foo.append() with only one argument (an int), the exception complains that it needs a list and not an int.

Note: This is not a special feature of the list class. All instance methods can be called in both forms: some_object.func(a, b, c) or SomeType.func(some_object, a, b, c)

Upvotes: 0

Prune
Prune

Reputation: 77837

The first one sets foo to the object list. This is not an empty list, as you've discovered. The object list is a built-in type ... and you now have an in-scope alias to the type. You cannot append to a type; hence the error message.

The other two are classic ways to initialize a variable to an empty list. The middle one uses list literal notation to construct a list, while the last one invokes the list type object as a function to generate an instance of the type.

Upvotes: 4

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

When you're doing foo = list, you're actually assigning foo to a built-in python object of list. bar = list() and baz = [] both initiates two new variables as new vacant list. However in python var_ = [] assigning is a bit faster compared to var_ = list().

Upvotes: 2

Related Questions