In our Part 7 of Python series we learned about different types of functions in Python, today in this tutorial we will learn the concepts of Arrays (Lists) in Python. So let’s get started.
What are Lists?
A list (array) is a set of objects. Individual objects can be accessed using ordered indexes that represent the position of each object within the list.
Your manager asked you to write a Python program that accepts some numbers from the user. Once entered, the numbers should be stored someway. Then the stored numbers should be sorted in ascending and descending orders, and printed to the user in both cases.
Ah, and the most important requirement is that the program should keep asking the user for input until the user enters -99999. At this point the program stops prompting for new numbers, starts processing, and finally prints the sorted numbers. This means the number of the user’s input numbers is variable.
Now, the big question: How would you achieve this requirement? How could you store a variable number of inputs (which you don’t know in advance)?
Lists will give us the answer, soon.
* * * * * *
The following is a list containing four elements:
To read the content of the first element, and assign it to the variable x:
To set the value of the fourth (last) element to 0:
To access the first element of an array, the element at index 0 is referenced; myarray. To access the second element, the element at index 1 is referenced; myarray, and so on. As a general rule, to access the nth element of an array, refer to the element at index n-1.
* * * * * *
Let’s get more familiar with lists by taking some examples.
The len() function
The len() function takes a list as an argument, and returns the length of the list.
The list named myarray contains four elements, so the output of len(myarray) is 4.
Accessing the last element in a list
To access the last element in an array, we can do it using either of two ways:
- Using the Negative index:
So, myarray[-1] is exactly equivalent to myarray[length(myarray) – 1]
Both methods have the same effect, so you are free to use either one.
* * * * * *
Slicing can be defined as taking a subset of an existing array to create a new one.
When we say subarray = myarray[1:3] , we are asking the interpreter to declare a new array called subarray, and initialize it with values from myarray. This is exactly equivalent to:
Passing Lists as arguments to functions
Lists can be passed to functions as arguments, just like ordinary variables. We have already tried this when we talk about the len() function.
To simplify the idea, consider the following script that declares a function avg_list that takes a list as its argument, and returns the average of the list.
Let’s explain things:
- First the function is defined using the def statement, with one argument specified.
- The variable that will store the (accumulative) total is initialized to 0.
- A for loop is needed to loop on the elements of the passed list (mylist). So, the loop variable i will take all the possible values from the range 0 up to the length of the array mylist (excluding the upper value: len(mylist)) .
- The elements of the array mylist are referenced one after another (using the loop variable as index). In each iteration, the value of the element is added to the variable total.
- At last the average is calculated and returned to the calling statement.
Simple and logic, huh!!
* * * * * *
Getting Minimum and Maximum values in a list
To get the element having the minimum value in a list, use the min() function:
Similarly, to get the element having the maximum value in list, use the max() function:
Appending to Lists
There will be cases (like the one we will discuss soon) that you will need to add (append) a new element to an existing array. To do this, use the list.append() method:
A list can be sorted using the sort() method:
A list can have its elements reversed using the reverse() method:
* * * * * *
Back to the example I gave you earlier in this article under section Why Lists.
Now, and after gaining some fair knowledge about lists, have you had an idea on how to write the required program?
Check the following script:
Let’s execute it, and see what will happen:
Have you seen that?! It worked!!!
Now, to the explanation:
- Line 1: declares the empty list user_input.
- Line 2: starts an infinite loop.
- Lines 3-6 : the loop body:
- Line 3: prompts the user to input a number. After being evaluated, the number is assigned to the variable x.
- Line 4: checks if the input equals -99999 (the exit condition). If so, Line 5 executes the break statement that exits the loop.
- Line 6: if the input doesn’t meet the exit condition, this line is executed. It appends the input number to the list user_input.
- Line 7: prints the resulting list of numbers user_input.
- Line 8: uses the sort() method to restructure the user_input array, by sorting its elements in Ascending order.
- Line 9: prints the sorted list.
- Line 10: reverses the order of list (which has been sorted in ascending order). This reverses the order to be Descending.
- Line 11: prints the reversed list.
Simple, logic, and straightforward, isn’t it?!
* * * * * *
In this article, we have tackled a very important concept: Lists. Lists are useful for storing and processing related collections of data.
See you in another series, and another topic.
Python is among the most important programming languages today and can be used in SPSS. Doing so may truly decimate the time and effort you need to get things done. This tutorial briefly explains what Python is, how it relates to SPSS and why you might want to start using it.
What is Python?
- Python is among the most important programming languages in use today. It is Open Source Software and it may be freely downloaded, used and distributed, even for commercial use.
- Python was deliberately designed to be intuitive and easy to learn, a programming language suitable for non programmers -which probably includes most SPSS users.
- Python easily handles a huge variety of tasks: it can read, write or modify text files, Excel files, MySQL databases, SPSS and much more. The website you're now visiting also runs partly on Python.
- Just like www.spss-tutorials.com, Python was invented and created in Amsterdam, the Netherlands.
How does Python relate to SPSS?
- Python and SPSS are two separate programs that used to be completely unrelated. You could have both on your computer but they would not cooperate to any extent whatsoever.
- Since SPSS version 13, an SPSS Python plugin was developed. It connects SPSS with Python and thus makes everything in Python available to SPSS and reversely.
- The plugin allows using Python code in the SPSS syntax window. SPSS sends this Python code to Python
- Python may then retrieve elements from SPSS such as variable names, data values, output tables and charts.
- Finally, Python can modify these elements or create and run SPSS syntax based on what's in the data or output windows.
- Starting from SPSS version 17, you can run SPSS syntax (with or without Python) from SPSS Custom Dialogs that can be easily added to SPSS’ menu. Custom dialogs can have Python do the work for you without even seeing it. Some of the custom dialogs that we built are found under tools.
Why Should I Use Python in SPSS?
- First and foremost, using Python for larger or more complex tasks may decimate the amount of time and effort they require.
- Second, using Python may drastically decrease the amount of syntax needed in order to complete some tasks. Shorter syntax is much easier to read, modify and debug.
- Copy-pasting large amounts of syntax is a waste of time and often results in mistakes.
- Some SPSS tasks are not possible at all with basic syntax but are easily accomplished by Python.
- There are no costs associated with using Python in SPSS.
- There's an ever growing number of SPSS Custom Dialogs and SPSS Extension Bundles freely available that can be used from SPSS’ menu but still need Python to actually run.
- Some really crazy people even think that SPSS with Python is much more fun than just SPSS.