Page 84 - Information_Practice_Fliipbook_Class11
P. 84
4.1.3 Sequence Data Types
A Python sequence is an ordered collection of items indexed by the positions of the elements in the sequence. The first
element in a sequence is at index value 0 (zero), the second element at index 1, the third element at index 2, and so
on. In this chapter, we discuss three types of sequences, namely, strings, lists, and tuples.
● String (str) : A string refers to a sequence of characters. These characters may include alphabets, digits, special
characters, and spaces. A string may be enclosed within single quotation marks (for example, 'India') or double
quotation marks ( for example, "India"). Note that the quotation marks are not part of the string. They just mark
the beginning and end of the string. Arithmetic operations cannot be performed on a string. Some examples of
strings are
country = "India"
year = "1947"
message = "I love my country"
When a string is displayed in IDLE, it is enclosed in single quotation marks so that leading and trailing spaces can be
seen easily. As shown below, indexing is used to refer to an individual character of a string:
>>> country
'India'
>>> message
'I love my country'
>>> year
'1947'
>>> country[0] ……… displays the first character
'I'
>>> message[7] …. Displays the eighth character
'm'
● Lists (list): A list is a sequence of items, separated by commas and enclosed within square brackets:[]. The data
items in a list may be of the same or different types. For example,
>>> lst = [1, 2, 3, 4]
>>> lst1 = [1, 2, 1, 1, 2, 3, 4, 3, 2]
>>> myList = ['A101',"Bread", 2, 20]
>>> print(myList)
['A101', 'Bread', 2, 20]
>>> lst
[1, 2, 3, 4]
>>> lst1
[1, 2, 1, 1, 2, 3, 4, 3, 2]
The individual elements of a list are accessed using the index as shown below:
>>> lst[2] ……… Displays the third element
3
>>> myList[1] ……. Displays the second element
'Bread'
Indexes are also used to modify a list. For example,
>>> lst[0] = 10
>>> lst
[10, 2, 3, 4]
● Tuple: A tuple is a sequence of objects (not necessarily of the same type) enclosed in parenthesis: (). Just
like lists, data items in a tuple are separated by commas (,). However, there is a striking difference between a list
and a tuple. A tuple is an immutable object, i.e., once created, the values in a tuple cannot be changed using an
assignment operator. In contrast, we have already seen that a list is a mutable object, i.e., the values in a list can be
easily changed using an assignment operator.
70 Touchpad Informatics Practices-XI

