patrick-mooney
patrick-mooney

Reputation: 1486

Why does my result from *args begin with an empty list in Python 3?

I'm learning Python and have never used the arbitrary-number argument functions before, and I'm having trouble understanding why I'm getting what I'm getting. Specifically, I'm running this code:

class LocationList(list):
    def __init__(*pargs):
        print(pargs)
        print(len(pargs))
        for the_item in pargs:
            print(the_item)

the_location = LocationList('a location', 'another location')

And what I'm getting is this:

([], 'a location', 'another location')
3
[]
a location
another location

Why am I getting the empty list at the beginning?

I'm using Python 3.4.3 under Linux.

Upvotes: 0

Views: 64

Answers (3)

C. Hoffmann
C. Hoffmann

Reputation: 21

Methods within a class has self as the first argument, including

__init__()

To get the result I think you were looking for:

def __init__(self, *pargs):
    ...

Upvotes: 2

Ed Solis
Ed Solis

Reputation: 96

*pargs, since it is prefixed with '*' (an asterisk), collects all of the arguments into a tuple. Also, for class and object method definitions, the first argument is always "self", which is, in this case the object (or instance) that you create when you do this:

the_location = LocationList('a location', 'another location')

Further, your class is extending list:

class LocationList(list):

Therefore, self (the object) becomes a list:

([], 'a location', 'another location') # self == []

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

Because the first argument to a method is the object it is called on. And the object is a descendant of list. And an empty list prints as "[]".

Upvotes: 3

Related Questions