Home | | Computer Science 12th Std | Lists, Tuples

# Lists, Tuples

To enable us to implement the concrete level of our data abstraction, Some languages like Python provides a compound structure called Pair which is made up of list or Tuple.

Lists, Tuples

To enable us to implement the concrete level of our data abstraction, Some languages like Python provides a compound structure called Pair which is made up of list or Tuple. The first way to implement pairs is with the List construct.

## List

List is constructed by placing expressions within square brackets separated by commas. Such an expression is called a list literal. List can store multiple values. Each value can be of any type and can even be another list.

Example for List is [10, 20].

The elements of a list can be accessed in two ways. The first way is via our familiar method of multiple assignment, which unpacks a list into its elements and binds each element to a different name.

lst := [10, 20]

x, y := lst

In the above example x will become10 and y will become 20.

A second method for accessing the elements in a list is by the element selection operator, also expressed using square brackets. Unlike a list literal, a square-brackets expression directly following another expression does not evaluate to a list value, but instead selects an element from the value of the preceding expression.

lst

10

lst

20

In both the example mentioned above mathematically we can represent list similar to a set.

lst[(0, 10), (1, 20)] – where Any way of bundling two values together into one can be considered as a pair. Lists are a common method to do so. Therefore List can be called as Pairs.

## Representing Rational Numbers Using List

You can now represent a rational number as a pair of two integers in pseudo

code : a numerator and a denominator.

rational(n, d):

return [n, d]

numer(x):

return x

denom(x):

return x

## Tuple

Remember, a pair is a compound data type that holds two other pieces of data. So far,we have provided you with two ways of representing the pair data type. The first way is using List construct and the second way to implement pairs is with the tuple construct.

A tuple is a comma-separated sequence of values surrounded with parentheses. Tuple is similar to a list. The difference between the two is that you cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.

Example colour= ('red', 'blue', 'Green')

Representation of Tuple as a Pair

nums := (1, 2)

nums

1

nums

2

Note the square bracket notation is used to access the data you stored in the pair. The data is zero indexed, meaning you access the first element with nums and the second with nums.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
12th Computer Science : Chapter 2 : Data Abstraction : Lists, Tuples |