Menu Close

Tuples and Lists

In python, tuples and lists are variables that store multiple items and values. The main difference between tuples and lists is that lists are mutable after declaration, while tuples are not. Both are essential for writing code.

Declaration:

Tuples are declared using parentheses, with values that are separated by commas.

MyTuple = (“dogs”, “cats”, “horses”)

However, a list is declared using brackets instead of parentheses.

MyList = [“dogs”, “cats”, “horses”]

Indexes

In python, working with tuples and lists requires knowledge of how to use indexes. An index points towards an object within a list or tuple. For each of these datatypes, each item in the list or tuple has a corresponding number associated with it.

For example:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”]

In the list above, the index of Mercury is 0, the index of Venus is 1, and the index of Mars is 2.

It is important to remember that indexes always start at 0, as indexes represent the distance from the first element in the object rather than numbering from 1.

To access an element in a tuple or list, use the syntax ObjectName[indexValue]. This will access the item at the given index.

Negative Index Values

Many would assume that using a negative index value would be impossible, as there are no values before the first item in a list or tuple to access.

However, this is not the case. In python, negative values wrap around to the end of the list or tuple and count backward for the desired value. It is important to note that this is not the same the other way around, so inserting a value larger than the length of the object will throw an IndexError.

Example 1:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”]
print(Mylist[-1])

Output:

Mars

In this case, the index points to the last item in the list, as it looks for the first value from the end.

Example 2:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”]
print(MyList[4])

Output:

IndexError: list index out of range

In this case, the index of the list starts at 0. Therefore, the highest index the list goes to is 3. Because index 4 is outside the scope of this list, it throws an error as there is nothing to retrieve.

Access multiple elements

In python, the colon (“:”) is used to access multiple values inside a list or tuple.
There are two forms- single colons and double colons.

Single colons

Single colons are used to choose a start and endpoint for the values needed. The syntax is ObjectName[startIndex : endIndex]

The start index value is included, but the value at the index on the right is excluded.

Example 1:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”]
print(MyList[2:4])

Output

[“Earth”, “Mars”]

The output of this code displays the second index through to the third, which is Earth and Mars in this case. Notice how the output is in the form of another list. However, if we had used a tuple instead, the output would also be a tuple.

 

If we leave the value on the left or right of the colon blank, python makes that value the extremes of the list or tuple by default. A blank on the left will have that line of code start from index 0, and a blank on the right will have that line of code start from index n – 1, where n is the length of the list or tuple.

For this reason, the single colon can also be used to represent every object in a list or tuple. By writing the syntax MyObject[:], python interprets this as “for each object in MyObject”. The reason why you would use it is that by referencing the original object rather than only the values, the change to the first object will also change the second.

Consider the following segment of code:

List1 = [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”]
List2 = List1
List3 = List1[:]

List1.append(“Uranus”)
print(“List 2: “, List2)
print(“List 3: “, List3)

Output:

List 2: [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”]
List 3: [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”]

The example above shows that because List2 points to the List1 object itself, any changes made to List1 will be reflected when calling List2. However, List3 accesses every object inside List1 and creates a new list. Thus, any changes made to List1 will not affect List3.

Double colons:

The double colons have a similar syntax to the single colon, but it adds one more parameter—step. By using the syntax MyObject[startIndex : endIndex : step], it allows programmers to choose which elements are included. For example, by default, the step is 1. This means that every element is included. However, if the step is 2, only every second object is included.

Example 1:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”]
print(MyList[::2])

Output:

[“Mercury”, “Earth”, “Jupiter”]

Notice how when the left is blank, the first element in the tuple or list is always included.

Example 2:

MyList = [“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”]
print(MyList[1:4:2])

Output:

[“Venus”, “Mars”]

The first element is always included, and the skipped elements are counted from the value on the left.

Packing and unpacking

By putting values into a list or tuple, it is known as packing. Like what we did above, tuple packing follows the syntax of assignment.

However, unpacking requires taking values within a list or tuple and creating separate variables for them.

For example:

Tuple1 = (“Bed”, “Couch”, “Television”)
Furniture1, Furniture2, Furniture3 = Tuple1
print(Furniture1)

Output:

Bed

Here, we took all the values inside the tuple and created separate variables for them. This also works with lists.

Comparison between 2 lists or 2 tuples

Many would assume that the comparison between lists and tuples would be impossible as it has multiple values. However, this is not the case. Python has a system of choosing which list or tuple it believes is greater or lesser.

When comparing two lists or tuples, python will start by comparing the first value. If one list or tuple’s first is greater than the other’s, python will consider that list or tuple larger.

For example:

Tuple1 = (3, 4, 6, 2, 4)
Tuple2 = (1, 9, 8, 6, 7, 8, 9)
print(Tuple1 > Tuple2)

Output:

True

While the amount and sum of the elements in the second tuple is larger, python still considers Tuple1 larger because its first element is larger than Tuple2’s.

If the first value is the same, it will determine which is greater by the second element. If the second element is also the same, it will determine by the third element, and so on, and so forth.

For example:

Tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Tuple2 = (1, 2, 3, 4, 5, 6, 7, 8, 0)
print(Tuple1 < Tuple2)

Output:

False

Commands for lists and tuples

  • all()

    • The “all(iterable)” method will return true if all items in the list or tuple are True, or above 0.
    • Example:
      List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      List2 = [0, 1, 2, 3, 4, 5, True]
      print(all(List1), all(List2))

      Output:

      True False
  • any()

    • The “any(iterable)” method returns true if any item in the list or tuple is true.
    • Example:
      List1 = [False, False, 0, 1, 0]
      print(any(List1))

      Output:

      True
  • enumerate()

    • The “enumerate(iterable)” method returns tuples labeled from 0 to n – 1, where n is the length of the list or tuple.
    • Example:
      List1 = [“one”, “two”, “three”, “four”]
      List2 = enumerate(List1)
      print(list(List2))

      Output:

      [(0, “one”), (1, “two”), (2, “three”), (3, “four”)]
  • max()

    • The “max(iterable)” method returns the largest element in the list or tuple.
    • Example:
      List1 = [1, 2, 3, 4, 5, 6, 7]
      print(max(List1))

      Output:

      7
  • min()

    • The “min(iterable)” method returns the smallest element in the list or tuple.
    • Example:
      List1 = [1, 2, 3, 4, 5, 6, 7]
      print(min(List1))

      Output:

      1
  • sorted()

    • The “sorted(iterable, reverse)” method returns a sorted tuple or list from the elements inside the original iterable. The reverse parameter, if set to True, will sort the list or tuple from greatest to least.
    • Example:
      List1 = [3, 4, 3, 5, 5, 6, 7]
      print(sorted(List1))

      Output:

      [3, 3, 4, 5, 5, 6, 7]
  • tuple()

    • The “tuple(iterable)” method casts the object into a tuple.
    • Example:
      List1 = tuple([1, 2, 3, 4, 5, 6, 7])
      print(List1)

      Output:

      (1, 2, 3, 4, 5, 6, 7)
  • list()

    • The “list(iterable)” method casts the object into a list.
    • Example:
      List1 = list((1, 2, 3, 4, 5, 6, 7))
      print(List1)

      Output:

      (1, 2, 3, 4, 5, 6, 7)
  • index()

    • The “iterable.index(value)” method returns the first position of a given value.
    • Example:
      List1 = [1, 2, 3, 4, 5, 6, 7]
      print(List1.index(5)

      Output:

      4
  • append() *Lists only

    • The “list.append(value)” method adds a value to the end of a list.
    • Example:
      List1 = [1, 2, 3, 4, 5, 6, 7]
      
      List1.append(8)
      print(List1)

      Output:

      (1, 2, 3, 4, 5, 6, 7, 8)
  • Insert() *Lists only

    • The “list.insert(index, value)” method adds a value to the chosen index.
    • Example:
      List1 = [1, 3, 5, 7, 9]
      List1.insert(0, -1)
      print(List1)

      Output:

      [-1, 1, 3, 5, 7, 9]
  • pop() *Lists only

    • The “list.pop(index)” method removes the item at a given index and returns the item’s value.
    • Example:
      List1 = [1, 3, 5, 7, 9]
      print(List1.pop(0))
      print(List1)

      Output:

      1
      [3, 5, 7, 9]

 

  • remove() *Lists only

    • The “list.insert(index, value)” removes the item at a given index but does not return the item’s value.
    • Example:
      List1 = [1, 3, 5, 7, 9]
      List1.remove(0)
      print(List1)

      Output:

      [3, 5, 7, 9]
  • reverse() *Lists only

    • The “list.reverse()” method reverses a list.
    • Example:
      List1 = [1, 3, 5, 7, 9]
      List1.reverse()
      print(List1)

      Output:

      [9, 7, 5, 3, 1]
  • sort() *Lists only

    • The “list.sort(reversed)” method sorts a list from least to greatest. If the parameter reversed is set to True, the list will be sorted from greatest to least.
    • Example:
      List1 = [3, 4, 3, 6, 7, 8, 4]
      List1.sort()
      print(list1)

      Output:

      [3, 3, 4, 4, 6, 7, 8]

 

Posted in Articles, Embedded Programming Language, Python

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!