Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / artificial-intelligence / machine-learning

Python Tuples, Lists, Destructuring, and Loops

4.25/5 (5 votes)
15 Jun 2020CPOL4 min read 13.1K   111  
Now that you know some of the basics of Python we can go a bit deeper, with the lists and tuples data structures and see how to work with them.
Python offers lists and tuples as data structures for collections. This module talks about these and how you can use them with destructuring and loops.

Introduction

This is the second module in our series to help you learn about Python and its use in machine learning (ML) and artificial intelligence (AI).

Now that you know some of the basics of Python, which were discussed in the first module, we can go a bit deeper, with the lists and tuples data structures and see how to work with them.

Lists

A list is a collection of items. Lists are mutable: you can change their elements and their size. Thus they’re similar to a List<T> in C#, an ArrayList<T> in Java, and an array in JavaScript.

You can assign a list like this, and then access its elements by their zero-based index:

Python
foo = [1, 2, True, "mixing types is fine"]
print(foo[0]) # 1
foo[0] = 3
print(foo[0]) # 3

The append method adds an element at the end of the list. The insert method places an element at an index you specify:

Python
foo = [1, 2, 3]
foo.append(4)
print(foo) # [1, 2, 3, 4]
foo.insert(0, 0.5)
print(foo) # [0.5, 1, 2, 3, 4]

To remove an element at an index, use the del keyword:

Python
del foo[2]
print(foo) # [0.5, 1, 3, 4]

Tuples

A tuple is another type of collection of items. Tuples are similar to lists, but they’re immutable. A tuple gets assigned like this:

Python
foo = 1, 2, True, "you can mix types, like in lists"

You'll often see tuples formatted as (1, 2, "a"), with parentheses. Parentheses around tuple values are used to help with readability or if needed because of the context. For example, 1, 2 + 3, 4 means something different than (1, 2) + (3, 4)! The first expression returns a tuple (1, 5, 4) while the second returns (1, 2, 3, 4).

Image 1

Obtaining a value from a tuple works in the same way as from a list, foo[index], with index denoting the zero-based index of the element. You can see that tuples are immutable if you try to change one of the elements:

Python
foo[0] = 3 # will raise a TypeError

That would work fine for a list, but not for a tuple.

Image 2

A tuple also doesn't have the append, remove, and some other methods.

You can also return tuples from functions, and this is a common practice:

Python
def your_function():
    return 1, 2

This returns a tuple (1, 2).

If you want a tuple with only one element, put a comma after that element:

Python
foo = 1,

Negative Indices and Slices

Python's indices are more powerful than I've demonstrated so far. They offer some functionality that doesn’t exist in C#, Java, and the like. An example is negative indices, in which -1 refers to the last element, -2 refers to the second-last element, and so on.

Python
my_list = [1, 2, 3]
print(my_list[-1]) # 3

This works on both lists and tuples.

Also, you can take a slice of a list or a tuple by specifying the index of the starting, ending, or both starting and ending elements of the slice. This generates a new list or tuple with a subset of the elements. Here are a few examples to demonstrate:

Python
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:2]) # [1, 2]
print(my_list[2:]) # [2, 3, 4, 5]
print(my_list[:2]) # [0, 1]
print(my_list[0:4:2]) # [0, 2]
print(my_list[-3:-1]) # [3, 4]
print(my_list[::-1]) # [5, 4, 3, 2, 1, 0]

The slice notation is [start:stop:step]. If start remains empty, it's 0 by default. If end remains empty, it means the end of the list. The :step notation is optional. So ::-1 means "from 0 to the end of the list with step -1" and thus returns the list reversed.

Slices will never raise IndexErrors. When going out of range, they just return an empty list.

Destructuring

Imagine you have a tuple (or a list) with a known number of elements, three for example. And suppose you'd rather have three distinct variables, one for each tuple element.

Python offers a feature called destructuring (or unpacking) to break up a collection with a single line:

Python
my_tuple = 1, 2, 3
a, b, c = my_tuple

Now a = 1, b = 2, and c = 3.

This also works for lists:

Python
my_list = [1, 2, 3]
a, b, c = my_list

This is very useful when dealing with functions that return tuples, and there are plenty of these in the Python ecosystem, as well as when dealing with AI-related libraries.

Loops

You're probably familiar with three kinds of loops: for, foreach, and while. Python only offers while and foreach loops (which it does with a for keyword!). No worries, though. As we'll see later, it's very easy to create a loop that behaves exactly like a for loop.

Here’s a Python loop that iterates over a list:

Python
fruits = ["Apple", "Banana", "Pear"]
for fruit in fruits:
    print(fruit)

You can also iterate over tuples:

Python
fruits = "Apple", "Banana", "Pear"
for fruit in fruits:
    print(fruit)

Generally, you can use a for loop on every iterator. Iterators, and how you can create your own, will be discussed in more depth in later articles.

If you want a C-style for loop rather than a foreach loop, you can loop over the result of the range function, which returns an iterator over a range:

Python
for i in range(10):
    print(i)

The last printed number will be 9. This is equivalent to the following C snippet:

Python
for (int i = 0; i < 10; i++) {
    Console.WriteLine(i);
}

The range function offers more than just counting from zero up to a given number. You can specify a different starting number using range(x, 10), where x will be the first array element. You can specify the step size using a third argument, such as range(0, 10, 2).

Creating a range that counts from high to low goes like this: range(10, 0, -1). The first element will now be 10 and the last will be 1. Indeed, range(0, 10) is not the reverse of range(10, 0, -1), because the second argument won’t be included in the range.

A while loop in Python looks very similar to what you already know:

Python
while condition:
    # code

Python also offers break and continue statements that work exactly like the ones in C#, Java, JavaScript, and many other languages.

Python
while True:
    if input() == "hello":
        break

Conclusion

In this module, we looked at lists and tuples in Python, and learned about indexing, destructuring, and loops. In the next article, we'll talk about generators and classes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)