Informatics Practices · Ch 3 — Brief Overview of Python
Sequence
Sequence
A sequence in Python is an ordered collection of items in which each item is indexed by an integer value. Both halves of that definition matter. Ordered means the items have fixed positions — first, second, third — and the collection remembers that order. Indexed by an integer means each position carries a number, so any individual item can be reached by its position. Python offers three sequence data types: Strings, Lists and Tuples. All three are ordered, indexed collections; they differ in what they hold and in whether they can be changed.
String. A string is a group of characters. The characters may be alphabets, digits or special characters, including spaces. String values are enclosed either in single quotation marks (for example 'Hello') or in double quotation marks (for example "Hello") — the two forms are equivalent. The quotes themselves are not part of the string; they exist only to mark, for the interpreter, where the string begins and ends.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
The second assignment carries the crucial lesson. str2 holds "452", which looks like a number but is a string — a piece of text made of the digit characters 4, 5 and 2. Numerical operations cannot be performed on strings, even when the string contains a numeric value. A numeric string is still a string; you cannot do arithmetic with it.
"452" and 452 are entirely different values: the first is text, the second is a number. Anything wrapped in quotes is a string, whatever it looks like — and strings do not participate in numerical operations.
List. A list is a sequence of items separated by commas, with the items enclosed in square brackets [ ]. The items of one list may be of different data types — numbers, strings and decimals can sit side by side in the same list.
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
This single list mixes an integer (5), a float (3.4), strings ("New Delhi", "20C") and another integer (45). Typing the list's name in interactive mode displays all its elements in their original order — exactly what an ordered collection promises.
Tuple. A tuple is also a sequence of items separated by commas, but the items are enclosed in parentheses ( ) — unlike a list, where values are enclosed in square brackets [ ]. Like list items, tuple items may be of different data types. The defining difference is this: once a tuple is created, its items cannot be changed.
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, 'Apple', 3.4, 'a')
Again the items span several types — integers, a string, a float and a single character — and printing the tuple shows them in order. …