Pinterest Stumbleupon Whatsapp
Advertisement

Arrays and lists are some of the most useful data structures in programming — although few people really use them to their full potential. Today I’ll be talking you through the basics, along with some simple Python examples.

Prerequisites

There’s not a lot you need to know ahead of time in order to learn these concepts. A basic knowledge of programming paradigms and Python will be helpful, but it’s not required. Read our basic Python examples 10 Basic Python Examples That Will Help You Learn Fast 10 Basic Python Examples That Will Help You Learn Fast This article of basic python examples is for those who already have some programming experience and simply want to transition to Python as quickly as possible. Read More if you don’t know where to start. If you think Python is a useless language, check out our reasons why it isn’t 5 Reasons Why Python Programming Is Not Useless 5 Reasons Why Python Programming Is Not Useless Python -- You either love it or you hate it. You might even swing from one end to the other like a pendulum. Regardless, Python is a language that's hard to be ambivalent about. Read More .

While the following fundamental ideas can be applied to any language, I’ll be demonstrating the examples in Python. It is an easy language to learn and provides an excellent platform to understand what’s going on. In addition to this, tutorialspoint.com provides an excellent online Python interpreter — you don’t even have to install Python if you don’t want to (if you do, check out our guide to virtual environments Learn How to Use the Python Virtual Environment Learn How to Use the Python Virtual Environment Whether you are an experienced Python developer, or you are just getting started, learning how to setup a virtual environment is essential for any Python project. Read More ).

Data Structures

What is a data structure? At its most basic level, a data structure is a way of efficiently storing data. It’s easy to get confused because data structures are not data types. Data types tell the compiler (or in Python’s case the interpreter) how the data is intended to be used. Data structures specify operations that can be performed, and often implement specific rules and regulations.

You may have heard of some linear data types (elements are sequential):

  • Array
  • Matrix
  • Lookup Table

Similarly, lists often contain rules and methods to regulate how they operate. Some common lists are:

  • Linked List
  • Doubly Linked List
  • Array List or Dynamic Array

There is a plethora of different data structures. You may have heard of binary trees, graphs, or hashes. I’ll be discussing the basics today, but you may wish to learn more once you are comfortable.

Array

Let’s start at the beginning. An array is a simple collection of (related) values. These values are called elements. They can usually be any data type you like, including objects or other lists! The main caveat with arrays is that all the data has to be the same — you cannot store mixed strings and integers. You nearly always have to specify how many elements you would like to store. Variable size or dynamic arrays do exist, but fixed-length arrays are simpler to start with.

Python complicates things somewhat. It makes things very easy for you, but it does not always stick to strict definitions of data structures. Most objects in Python are usually lists, so creating an array is actually more work. Here’s some starter code:

from array import array
numbers = array('i', [2, 4, 6, 8])
print numbers[0]

The first line imports the array module — that’s required to work with arrays. The second line creates a new array called numbers and initializes it with the values 2, 4, 6, and 8. Each element is assigned an integer value called a key or index. Keys start at zero, so numbers[0] will access the first element (2):

Python Arrays

You may be wondering what the ‘i’ is used for. This is a typecode that tells Python the array will be storing integers. This sort of thing would not normally be needed in Python (it would be considered “unpythonic”). The reason for this is simple. Arrays in Python are a very thin wrapper on the underlying C arrays of your operating system. This means they are fast and stable, but they may not always adhere to the Python syntax.

You cannot store mixed types in these arrays. Say you wanted to store the string “makeuseof.com”:

numbers = array('i', [2, 4, 6, "makeuseof.com"])

This will not be allowed and will throw an exception:

Python Arrays

Here’s how you can print all the elements:

print numbers

Python Arrays

This method of accessing array elements works well, and it is perfect for the right task. What it’s not good for is accessing the whole array. Programmers are inherently lazy, so I’ll happily write more, better code, if it means I can make maintenance easier, and reduce copy & paste effort.

Every programming language will implement a loop of some sort, which are perfect for iterating (looping) over list elements. The most common loops are while and for. Python makes things even easier by providing a for in loop:

for number in numbers:
    print number

Notice how you did not have to access elements by their key. This is a much better way of working with an array. An alternative way to iterate over a list is with a for loop:

for i in range(len(numbers)):
    print numbers[i]

This does exactly the same thing as the previous example, although you have had to specify the number of elements in the array (len(cars)), along with passing i as the key to the array. This is almost exactly the code that for in loops run. This way provides slightly more flexibility, and is slightly faster (although for in loops are more than fast enough the majority of the time.)

Lists

Now that you know how arrays work, let’s look at a list. It can be confusing sometimes, as people use different terminology interchangeably, and lists are arrays… kind of.

A list is a special type of array. The biggest difference is that lists can contain mixed types (remember, arrays must contain elements of the same type). Lists are very easy in Python:

cars = ['Ford', 'Austin', 'Lancia']

Notice how you don’t need to import the array module?

This syntax declares a list called cars. Inside the square brackets, each element of the list is declared. Each element is separated by a comma, and as each element is a string, you declare them inside quotes. Python knows this is an object, so the print statement will output the content of the list:

print cars

Python Arrays

Just like with the array, you can iterate list elements over using loops:

for car in cars:
    print car

Python Arrays

The real party trick of lists is their mixed type. Go ahead and add some extra data:

cars = ['Ford', 'Austin', 'Lancia', 1, 0.56]

This is no problem for Python — it did not even raise an exception:

Python Arrays

It’s easy to add new elements to a list (something not possible with arrays):

cars = ['Ford', 'Austin']
print cars
cars.append('Lancia')
print cars

Python Arrays

You can also merge two lists into one:

cars = ['Ford', 'Austin']
print cars
other_cars = ['Lotus', 'Lancia']
cars.extend(other_cars)
print cars

Python Arrays

It’s just as easy to remove elements using the remove syntax:

cars = ['Ford', 'Austin', 'Lotus', 'Lancia']
print cars
cars.remove('Ford')
print cars

Python Arrays

That about covers the basics of lists and arrays in Python. Why not consider a coding project, such as reading and writing to Google Sheets How to Read and Write to Google Sheets With Python How to Read and Write to Google Sheets With Python Python may seem strange and unusual, however it is easy to learn and use. In this article, I'll be showing you how to read and write to Google Sheets using Python. Read More , reading json data How to Get Python and JavaScript to Communicate Using JSON How to Get Python and JavaScript to Communicate Using JSON Today I'll be showing you how to use JSON to send data from JavaScript to Python. I'll be covering how to setup a web server, along with all the code you need. Read More . Maybe you could put your new skills to use making some custom shortcut buttons Make Your Own Custom Shortcut Buttons With an Arduino Make Your Own Custom Shortcut Buttons With an Arduino The humble Arduino can do a lot of things, but did you know it can emulate a USB keyboard? You could combine long keyboard shortcuts into a single custom shortcut key, with this simple circuit. Read More . Despite being a different programming language, these array principles still apply.

Have you learnt anything new? Would you like to see some more complicated content? Let us know your thoughts in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *