Computer Science · Ch 5 — Getting Started with Python
Sequence
Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer — the position of every element is fixed and numbered. Python offers three sequence data types: Strings, Lists and Tuples. Each gets a detailed chapter later; here is what distinguishes them.
(A) String
A string is a group of characters — alphabets, digits or special characters, including spaces. String values are enclosed either in single quotation marks (e.g., 'Hello') or in double quotation marks (e.g., "Hello"). The quotes 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"
A crucial caution: numerical operations cannot be performed on strings, even when the string happens to contain a numeric value. str2 above holds the characters "452", not the number 452 — arithmetic on it is an error until it is converted to a numeric type.
(B) List
A list is a sequence of items separated by commas and enclosed in square brackets [ ]. A single list may freely mix data types — integers, floats and strings side by side (Example 5.4):
#create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
A tuple is likewise a sequence of comma-separated items, but the items are enclosed in parentheses ( ) — unlike a list, whose values sit in square brackets. The deeper difference is behavioural: once created, a tuple cannot be changed (Example 5.5):
#create a tuple
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')