VariableList Class (Python)

The VariableList class provides access to the variables in a dataset, allowing you to get and set properties of existing variables, as well as add new variables to the dataset. You get an instance of the VariableList class from the varlist property of the Dataset class, as in:

datasetObj = spss.Dataset('data1')
varListObj = datasetObj.varlist

The number of variables in a VariableList instance, which is also the number of variables in the associated dataset, is available using the len function, as in:

len(varListObj)

Note: An instance of the VariableList class can only be created within a data step, and cannot be used outside of the data step in which it was created. Data steps are initiated with the spss.StartDataStep function.

Looping through the variables in an instance of VariableList. You can loop through the variables in an instance of the VariableList class, obtaining a Variable object (representing the properties of a single variable) on each iteration. For example:

for var in datasetObj.varlist:
   print var.name
  • On each iteration of the loop, var is an instance of the Variable class, representing a particular variable in the VariableList instance. The Variable class allows you to get and set variable properties, like the measurement level and missing values. See the topic Variable Class (Python) for more information.

Accessing a variable by name or index. You can obtain a Variable object for a specified variable in the VariableList instance. The desired variable can be specified by name or index. For example:

#Get variable by name
varObj = datasetObj.varlist['salary']
#Get variable by index
varObj = datasetObj.varlist[5]

Deleting a variable. You can delete a specified variable from the VariableList instance, which results in deleting it from the associated dataset. The variable to be deleted can be specified by name or index. For example:

#Delete variable by name
del datasetObj.varlist['salary']
#Delete variable by index
del datasetObj.varlist[5]