Python for Beginners 18: Lists and Tuples

In this lesson, we are going to transfer our knowledge on operations we can do with strings to new sequence-based data types, namely lists and tuples. Both are, like the name list indicates, an enumeration of elements.

Let’s look at an example for each of them:

  • To create a list, you can simply enclose the elements in square brackets ([]). You can also create an empty list without any elements using empty brackets, [].
    myFirstList = [a, 3, “red”]
  • A tuple (pronounced like it rhymes either with “supple” or with “quadruple”) does not require brackets, but may have a round brackets and it is going to be shown in round brackets when you print it.
    myFirstTuple = a, 3, “red” To create one with a single element, you have to include a final comma (to distinguish it from being a “normal”, non-sequential variable).

Overview of sequence-based data types: lists, tuples, strings

As the sequence-based data types can seem quite similar, it’s useful to compare them.

To break a string into individual letters and convert it into a list or a tuple, you can use the list or the tuple function, respectively.

Particularities of operations with lists and tuples

The 4 general operations mentioned in the lesson on strings also work for lists and tuples: You can access elements with the bracket operator, you can use the slice operator and you can do a traversal. However, there are some peculiarities.

For the relational operators there are two things to keep in mind:

  • With lists or tuples, bigger (>) and smaller (<) are considered as “bigger or equal” (>=) and “smaller or equal” (<=), respectively.
  • Subsequent elements in a position are not considered, i.e. if one list has a 1 as an element and the other list has 10 in the position, the result would be True, because Python considers the 1 as the first element of this position and ignores the subsequent 0.

useful methods for lists:

list methods:

  • lst.append() to add elements to the end of lst
  • lst.extend(lst2) to append all of the elements of lst2 to lst
  • lst.sort() arranges the elements of lst from low to high or in alphabetical order

Most list methods are void; they modify the list and return None. Thus, they are not valid for tuples, which cannot be modified.

string methods that involve lists:

  • string_name.split([delimiter]): converts a string into a list of words, the optional argument called a delimiter specifies which characters to use as word boundaries (default: blank space)
  • delimiter.join(list_name): takes a list of strings and concatenates the elements based on the delimiter

more useful functions

  • sum(lst) to add up the elements of a list (only possible if of the same type)
  • sorted(seq): takes a sequence and returns a new list with the same elements in sorted order
  • reversed(seq): takes a sequence and returns an iterator that traverses the list in reverse order

3 ways to delete elements from a list

  • lst.pop(index): deletes the element in the position of the index from the list and returns it → if you don’t indicate an index, the default is the last element
  • del lst[index]: deletes the element in the position of the index (or a slice of indices) from the list
  • lst.remove(element): deletes the element from the list and returns None

Which sequence to choose: lists vs. tuples?

As lists are mutable, they are more common than tuples. However, in some cases, it’s better to use tuples, for instance, because …

  • … tuple assignment makes it possible to swap the values of two variables without using a temporary variable or to use the split method to separate a sequence and assign the parts to a tuple
    a, b = b, a
  • … a function can only return one value, but it can be a tuple, so basically, it’s like returning multiple values

Example exercise

Create a program that asks the user for a certain amount of numbers (floating point). Store those numbers in a list. Show to the user the total, average and standard deviation of those numbers.
At the end, convert your list into a tuple.

This is what the result could look like.

If you want to learn more, I recommend once again Allen B. Downey’s Think Python, whose chapters on lists and tuples also inspired this post.

#mastery17

Leave a comment