Page 151 - Computer Science Class 11 Without Functions
P. 151
So far, we have dealt with individual data elements. But, at times, one must deal with several data values, say, names
of cities, marks of five subjects, details of items in a store, and so on. Sequence types available in Python are often used
to deal with aggregates of objects.
7.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 will 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]
Data Types and Operators 149

