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 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[0]
10
lst[1]
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.
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[0]
denom(x):
return x[1]
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[0]
1
nums[1]
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[0] and the second with nums[1].
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.