Introduction - Sequence Types
- Sequence types are ordered collections of objects.
- Elements are indexed using integers, starting from
0
. - Sequence types are container objects.
Indexing Sequence
- The first element is at index 0.
- The last element is at index (n-1), where N is the length of the sequence.
Homogeneous vs Heterogeneous Sequence
- Homogeneous : All elements in the sequence have the same type.
- Heterogeneous: Elements in the sequence can have different data types.
Type | Description |
---|---|
list | List (串列) - mutable, heterogeneous sequence |
tuple | Tuple (元組) - immutable, heterogeneous sequence |
str | String (字串)- immutable, homogeneous sequence |
Lists
Features of a List
- Lists are container and sequence types.
- Lists are mutable; elements can be added, replaced, and removed.
- Lists can be heterogeneous.
- Lists support unbounded growth, allowing the addition of as many elements as needed.
- Lists are objects.
- State: the elements contained in the list
- Functionality: add element, remove element…
List Literals
Lists are written within square brackets [ ]
, with elements separated by commas ,
.
# Homogeneous list
[10, 20, 30, 40]
# Heterogeneous list
[10, True, 3.14]
# Nested list
[10, 20, 30.5, [True, False]]
Accessing List Items by Index
l = [10, 20, 30, 40, 50] # length is 5
# index 0 1 2 3 4
# Reference an element by its index l[i]
>>> l[0]
10
>>> l[2]
30
>>> l[5] # the index is greater than last index
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Sequence Length
Use the len()
method to get the length of a list.
>>> l = [10, 20, 30, 40, 50]
>>> len(l)
5
>>> len([True, False])
2
Empty Lists
>>> l = []
>>> len(l)
0
Replacing a List Element
>>> l = [10, 20, 30, 40, 50]
>>> l[2] = True # replace l[2] by the assignment operator
>>> print(l)
[10, 20, True, 40, 50]
Coding
Use the type()
method to get the type of an object.
>>> l = [10, 20, 30, 40, 50]
>>> type(l)
<class 'list'>
Python supports negative index (start from -1
).
>>> l = [10, 20, 30, 40, 50]
>>> l[-1]
50
>>> l[-5]
10
To get the last element in the list.
>>> l = [10, 20, 30, 40, 50]
>>> l[len(l)-1]
50
>>> l[-1]
50
Additional
Access elements in a nested list using indexes.
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
>>> L[2]
['cc', 'dd', ['eee', 'fff']]
# To get the elements in a sublist, just append an additional index
>>> L[2][0]
'cc'
>>> L[2][2]
['eee', 'fff']
>>> L[2][2][0]
'eee'
Tuples
Features of a Tuple
- Tuples are container and sequence types.
- Tuples can be heterogeneous.
- Tuples are immutable; once created, elements cannot be changed.
Tuple Literals
Tuples are written within round brackets ( )
, with elements separated by commas ,
. The round brackets are optional.
(10, 20, 30, 40) # can be 10, 20, 30, 40
(10, (5, 50), 3.14)
((10, 20), 30.5, [True, False])
When a tuple is inside another tuple, ( )
is needed.
>>> t1 = 10, (5, 50), 3.14
>>> t2 = 10, 5, 50, 3.14
>>> len(t1)
3
>>> len(t2)
4
Indexing, Length
Use the index operator []
to access an item in a tuple (similar to lists). The len()
method works as well.
Tuples are Immutable
Tuples are generally immutable, but if the elements inside the tuple are mutable, changes are allowed.
>>> t = 10, 20, [True, False]
>>> id(t)
2201250959296
>>> t[2] = 100 # Can't change the list object to the integer object
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[2][1] = True # Change the element inside the list object
>>> t
(10, 20, [True, True])
>>> id(t)
2201250959296
Empty Tuples
t = ()
# Use tuple() function
t = tuple()
An empty tuple is not useful since tuples are unchangeable and will remain empty forever.
Coding
Sequence conversions (list ↔ tuple).
# list to tuple
>>> l = [1, 2, 3]
>>> t = tuple(l)
>>> t
(1, 2, 3)
# tuple to list
>>> t = 10, 20, 30
>>> t
(10, 20, 30)
>>> l = list(t)
>>> l
[10, 20, 30]
Replace elements in a tuple using sequence conversions.
>>> t = 10, 20, 30 # id(t): 1196275769472
>>> l = list(t) # change type to list
>>> l
[10, 20, 30]
>>> l[2] = 50
>>> l
[10, 20, 50]
>>> t = tuple(l)
>>> t
(10, 20, 50)
>>> id(t)
1196275769536
Strings
Features of a String
- Strings are container and sequence types.
- Strings are homogeneous, containing single Unicode characters.
- Strings are immutable.
String Literals
Strings are created using string delimiters (quotes '...'
or double quotes "..."
).
'this is a string'
"this is a string"
"Python's features:" # the delimiters are double quotes
'Python\'s features:' # escape character for quotes within strings
Indexing, Length
Use the index operator []
to access elements of the string. The len()
method gets the length of the string.
>>> s = 'Python rocks!'
>>> len(s)
13
>>> s[0]
'P'
>>> s[len(s) - 1]
'!'
>>> s[-1]
'!'
Coding
Strings are immutable.
>>> s
'Python'
>>> s[0] = 'p'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Empty Strings
>>> a = ''
>>> b = ""
>>> type(a), len(a), type(b), len(b)
(<class 'str'>, 0, <class 'str'>, 0)
>>> S = str()
>>> type(S), len(S)
(<class 'str'>, 0)
Type Conversions
>>> t = 1,2,3
>>> t
(1, 2, 3)
>>> s = str(t)
>>> s
'(1, 2, 3)'
>>> len(s)
9
>>> s[0]
'('
>>> s[8]
')'
>>> s = "ABCDEFG"
>>> l = list(s)
>>> l
['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> t = tuple(s)
>>> t
('A', 'B', 'C', 'D', 'E', 'F', 'G')
Multiplying str / list / tuple
>>> s1 = '*' * 5
>>> s1
'*****'
>>> t1 = (1,2,3) * 2
>>> t1
(1, 2, 3, 1, 2, 3)
>>> L = [0,0] * 3
>>> L
[0, 0, 0, 0, 0, 0]
# The repeated element is the same element repeated any times.
>>> t = ([10,20],30)
>>> t2 = t * 3
>>> t2
([10, 20], 30, [10, 20], 30, [10, 20], 30)
>>> t[0] is t2[0]
True
>>> t[0] is t2[2]
True
>>> t2[0] is t2[2]
True
>>> t[0][0] = 0
>>> t2
([0, 20], 30, [0, 20], 30, [0, 20], 30)
Slicing
[start:end]
- Access a range of elements in a sequence.
- The
start
index is inclusive of the element (default is 0). - The
end
index is exclusive of the element (default is the length of the sequence).
- The
- Returns a new slice object with the given values.
# index 0 1 2 3 4
>>> l = [1, 2, 3, 4, 5]
>>> l[0:2]
[1, 2]
>>> l[1:-1]
[2, 3, 4]
# index 0 1 2
>>> t = 10, 20, 30
>>> t
(10, 20, 30)
>>> t[0:2]
(10, 20)
# index 012345678
>>> s = 'Good Bye!'
>>> s[5:8]
'Bye'
>>> s[5:] # up to the maximal index
'Bye!'
# python allows slice() function to specify the index that is out of range.
>>> s[5:100]
'Bye!'
# leave out start/stop value
>>> s[:4] # Default is 0
'Good'
>>> s[:] # shallow copy
'Good Bye!'
Slicing with Steps
Negative Steps
When using negative step values:
- Starts at index
start
(inclusive). - Stops at index
end
(exclusive). - Moves backward (
start
should be greater thanend
).
#index 0 1 2 3 4 5 6 7 8 9
>>> l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> l[9:6:-1]
[100, 90, 80]
>>> l[:6:-1] # the start is not at 0, since it moves backwards
[100, 90, 80]
>>> l[3::-1] # the end here will be the beginning of the sequence
[40, 30, 20, 10]
>>> l[::-1]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
# Slicing works for string
# index 012345678
>>> s = 'Good Bye!'
>>> s[9:5:-1]
'!ey'
>>> s[:5:-1]
'!ey'
>>> s[::-1]
'!eyB dooG'
>>> s[8::-2]
'!y oG'
Coding
Slicing lists returns a new list, but the elements are the same objects as the original ones.
>>> L1 = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
>>> L2 = L1[0:2]
>>> L2
[[0, 0, 0], [1, 1, 1]]
>>> L1 is L2 # L2 is a new object
False
>>> L2[1] = "Python" # Mutating the list L2 doesn't affect L1
>>> L2
[[0, 0, 0], 'Python']
>>> L1
[[0, 0, 0], [1, 1, 1], [2, 2, 2]]
>>> L1[0] is L2[0] # But L1[0] and L2[0] are the same object
True
>>> L2[0][0] = 100 # Mutating the element inside L2[0] will affect L1[0]
>>> L1
[[100, 0, 0], [1, 1, 1], [2, 2, 2]]
>>> L2
[[100, 0, 0], 'Python']
Negative Slice
>>> s = 'abcdef'
>>> s[-4]
'c'
>>> s[-1]
'f'
>>> s[-4:-1] # Default step is 1, move from left to right
'cde'
>>> s[-1:-4] # Slicing from left to right will
''
>>> s[-1:-4:-1] # slicing from right to left
'fed'