Lecture
4 Strings, Tuples, and Arrays
So far we have
seen three data types: int, float, and string. Strings are
qualitatively
different from the other two because they are made up of smaller
pieces and characters.
1. Access the string
The bracket operator selects a single character from a string. The
expression fruit[1]
selects character number 1 from fruit.
Negative index:
2. Length
3. Strings are immutable:
You cannot create a string: "Jello, world" using the following method.
However, the following way method works:
4. The find() function
In
a sense, find is the opposite of the [] operator. Instead of taking an
index and extracting the corresponding character, it takes a character
and finds the index where that character appears. If the character is
not found, the function returns -1..
str.find can find substrings, not just characters:
Also, it takes an additional argument that specifies the index it
should start at:
Or it can take two additional arguments that specify a range of indices:
'-1' here is just a wrong answer. The range (1, 4) doesn't cover the
letter 'e' in 'bobie'. Try if you put (1, 3) as the range, it
will report '-1' as well.
5. Tuples
There
is another type in Python called a tuple that is similar to a list
except that it is immutable. Syntactically, a tuple is a
comma-separated
list of values.
Tuples are in
Parentheses!!!!!
Lists work well for storing sets of
items that can change throughout the life of a program. The ability to
modify lists is particularly important when you’re working with a list
of users on a website or a list of characters in a game. However,
sometimes you’ll want to create a list of items that cannot change.
Tuples allow you to do just that. Python refers to values that cannot
change as immutable, and an immutable list is called a tuple.
A
tuple looks just like a list except you use parentheses instead of
square brackets. Once you define a tuple, you can access
individual
elements by using each item’s index, just as you would for a list.
Although it is not necessary, it is conventional to enclose tuples in
parentheses:
To create a tuple
with a single element, we have to include the final comma:
Access the
elements of a tuple and add elements to a tuple. (still using brackets
for the indcies to access the tuples)
It may be confusing now, let's summarize the list, string, and tuples
before we move forward:
The list and the index works in this way:
If we want to add a new element to a list, the element must be a list:
However,
if you want to add something to a tuple in the same way, you'll fail
since tuple is immutable:
Definitely it will not work if you want to add a list into a tuple, it
just won't allow you to add anything there:
The only way to add something to a tuple is to attach something to it:
Intergers in a tuple:
Lists in a tuple:
and interestingly, it is mutable:
A tuple in a list:
The list is mutable but when it comes to modifying the elements in a
tuple, it becomes immutable.
6. Arrays (Matrices)
We've
beening working with matrices extensively in Matlab. Matlab is a really
neat tool to deal with matrices and their operations.
In Python, there is a very powerful function package
called 'Numpy' to deal with matrices.
NumPy is the
fundamental package for scientific computing in Python. It is a Python
library that provides a multidimensional array object, various derived
objects (such as masked arrays and matrices), and an assortment of
routines for fast operations on arrays, including mathematical,
logical, shape manipulation, sorting, selecting, I/O, discrete Fourier
transforms, basic linear algebra, basic statistical operations, random
simulation and much more.
NumPy’s main object is the homogeneous
multidimensional array. It is a table of elements (usually numbers),
all of the same type, indexed by a tuple of positive integers. In NumPy
dimensions are called axes.
For example:
The .arange() function will generate a series of number in a certain range in AN ARRAY!
Try this:
np.array([1,2,3], [1,2,3]). Why this one has syntax errors?
You need a bracket to put the two lists in. The correct version is: np.array([[1,2,3], [1,2,3]]).
7. Array creation
There
are several ways to create arrays. For example, you can create an array
from a regular Python list or tuple using the array function. The type
of the resulting array is deduced from the type of the elements in the
sequences.
From tuples:
Question: are these elements MUTABLE in a matrix created from a tuple?
-- YES.
From a list:
The same result!
But you cannot put discrete lists in the np.array() function, it has to
be in the brackets.
Like what you did in Matlab, you can create an array of ZEROs and ONEs:
To create sequences of numbers, NumPy provides a function analogous to
range that returns arrays instead of lists.
When
arange is used with floating point arguments, it is generally not
possible to predict the number of elements obtained, due to the finite
floating point precision. For this reason, it is usually better to use
the function linspace that receives as an argument the number of
elements that we want, instead of the step:
Remember?
We used 'from math import pi' in the second lecture. Both 'math' and
'numpy' package have the 'pi' constant in there. Import either one,
then you can directly use 'pi' in your code.
Printing arrays:
An alternative way to create the same array is to create a 1D array
first, and then reshape it:
8. Basic operations
Arithmetic operators on arrays apply elementwise. A new array is
created and filled with the result.
Keep in mind that, LISTs cannot do these operations by using these operators.
Apply the sin() function to the array:
Apply a logic operation:
Unlike
in many matrix languages, the product operator * operates elementwise
in NumPy arrays. The matrix product can be performed using the @
operator (in python >=3.5) or the dot function or method:
Some operations, such as += and *=, act in place to modify an existing
array rather than create a new one.
9. Universal functions: sum(), min(), max(), exp(), sqrt(), add() of the elements in an
array:
Tasks:
1.
I am trying to create a tuple called 'tuplee' and extract (access to but not deleting it) the string
'd' from the list in the tuple. Debugging the following code for this purpose:
2. There is a tuple called 'tupleee' which has three lists in it:
[1, 2, "3"], ["apple", "pineapple", "applepieeee"], [5, 6, "7"]
Please create this 'tupleee', access to the lists to modify 'applepieeee' to 'applepie'.
3.
The same 'tupleee' from Problem 2, replace the second and the third
lists in the tuple to a single-element list ["Replace"].
4. The same 'tupleee' from Problem 2, replace the second and the third
lists in the tuple to a string "Replace".
5. The same 'tupleee' from Problem 2, remove the second and the third
lists in the tuple and add a string "Replace" into the first list in tupleee.
6. Ceate a list 'listie', put three tuples in it:
('1', 1, [1]), ('2', 2, [2, 3, 4]), ('3', 3, [4, 5, 6])
Replace the last tuple in the list with a single string "haha"
7. The same list in Problem 6, listie, has three tuples in it:
('1', 1, [1]), ('2', 2, [2, 3, 4]), ('3', 3, [4, 5, 6])
Change the sublist [2,3,4] to [9, 9, 9]:
8. Create the following matrix A using two resources: from lists and from tuples.
9. Create a matrix from matrix A (in task 8) that has all the elements are cube of the elements in A.
10.
Assume the elements in A are angle degrees (in degree but not in
radians). Print a matrix B that has the same demension as A but the
elements are sinusoid of A.