Oh, pshaw!

 

cs490_august22

Page history last edited by pshaw 1 year, 3 months ago

List

In python, a list is basic data structure to represent a sequence of objects. This is not to be confused with term "Array", which is never used to represent anything in the core Python implementation.

A list is defined by '[' and ']' braces. A list containing no objects is simply '[]'. Examples of list:

>>> numbers = [10, 20, 30, 40]
>>> words = ["the","quick","brown","fox"]
>>> mixed = [10, "the", 20, "quick", 30, "brown"]

List elements can be reassigned and referenced by the same syntax as found in C or Java:

>>> numbers[1] = 25
>>> numbers[3] = [41,42,43] # (This embeds a list into a list)
>>> numbers[0] = numbers[2]

List can be concatenated:

>>> numbers = [10, 20, 30, 40]
>>> words = ["the","quick","brown","fox"]
>>> numbers + words
[10, 20, 30, 40, 'the', 'quick', 'brown', 'fox']
>>> numbers += [50] # This is a "push" stack operation
>>> numbers
[10, 20, 30, 40, 50]
>>> numbers = [5] + numbers # This is an "enqueue" queue operation
>>> numbers
[5, 10, 20, 30, 40, 50]

A list can be sliced by referencing the list with the colon operator inside the square braces. Think of slices boundaries as "fencepost" rather than "blocks". The first number and second numbers refer to the fencepost within the array (with the numbering starting at 0).

>>> [21,22,23,24,25][0]
21
>>> [21,22,23,24,25][0:5]
[21, 22, 23, 24, 25]
>>> [21,22,23,24,25][0:4]
[21, 22, 23, 24]
>>> [21,22,23,24,25][1:5]
[22, 23, 24, 25]
>>> [21,22,23,24,25][1:3]
[22, 23]
>>> [21,22,23,24,25][:1] # This is a "pop" stack operation
[21,22,23,24]
>>> [21,22,23,24,25][1:] # This is a "dequeue" queue operation
[22,23,24,25]

List can be sliced with negative values:

>>> [21,22,23,24,25][-1]
25
>>> [21,22,23,24,25][-2]
24

List can be sliced with a skip call:

>>> [21,22,23,24,25][1:4]
[22, 23, 24]
>>> [21,22,23,24,25][1:4:2]
[22, 24]
>>> [21,22,23,24,25][::-1] # This reverses a list
[25, 24, 23, 22, 21]

Boolean searches are simple in Python using "in" and "not in" operators:

>>> 21 in [21, 22, 23, 24, 25]
True
>>> 21 not in [21, 22, 23, 24, 25]
False
>>> 4 in [21, 22, 23, 24, 25]
False
>>> 4 not in [21, 22, 23, 24, 25]
True

Common built-in list operations:

>>> len([21, 22, 23, 24, 25]) # Length of a list
5
>>> min([21, 22, 23, 24, 25]) # Minimum value of a list
21
>>> max([21, 22, 23, 24, 25]) # Maximum value of a list
25
>>> sum([21, 22, 23, 24, 25]) # Sum of a list
115

Methods to the list object:

>>> numbers = [21,22,23,24,25]
>>> numbers.insert(2, 42) # Inserting element into list
>>> numbers
[21, 22, 42, 23, 24, 25]
>>> numbers.insert(10, 42) # Inserting element beyond the end of the list
>>> numbers
[21, 22, 42, 23, 24, 25, 42]
>>> numbers.pop(2) # Removes an element from a list an returns it.
42
>>> numbers
[21, 22, 23, 24, 25, 42]

Built-in method: range

"range" is a special built-in method for generating list sequences. A range can take 1, 2, or 3 arguments passed to it.

ArgumentsRange will return an list elements...
mfrom 0 to m-1
n,mfrom n to m-1
n,m,pfrom n to m-1, and skipping ever p numnbers

It's unclear why there is no way to generate the end bound number using range. I think that range when called with 2 or 3 arguments ought to return the end bound number with the list, but that's my opinion. This is a tad frustrating to programmers new to python.

>>> range(5)    # Generates 0 to 4
[0, 1, 2, 3, 4]
>>> range(1,5)  # Generates 1 to 4
[1, 2, 3, 4]
>>> range(0,10,2) # Generates even numbers from 0 to 8
[0, 2, 4, 6, 8]
>>> range(0,-10,-1) # Generates numbers from 0 to -9
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

Loops

There exist two loop constructs in Python: "while" and "for". "while" is a pre-conditional loop and acts just like it does in the C/C++/Java family of languages. There is no post-conditional "do while" construct in Python.

>>> i = 0
>>> while i < 10:
...     print i,
...     i = i + 1
... 
0 1 2 3 4 5 6 7 8 9

The "for" construct is a list iterator. To print a list of numbers in a sequence, you have to first generate a list of numbers. For that, it's best to use the "range" method:

"for" uses the following syntax:

foriterator variableinlist object:

>>> for i in range(10):
...     print i,
... 
0 1 2 3 4 5 6 7 8 9

The ideal use of the "for" construct is to iterate over a list.

>>> words = ["the","quick","brown","fox"]
>>> for w in words:
...     print w
... 
the
quick
brown
fox

Using the "range" and "len", we can get the positions of each element in a list:

>>> words = ["the","quick","brown","fox"]
>>> for i in range(len(words)):
...     print "%s: %s" % (i, words[i])
... 
0: the
1: quick
2: brown
3: fox

Methods

Methods are simple in Python:

defMethod Name(Comma separated arguments):

Because of duck typing, a method can return any data type it wants. It is the programmer's responsibility to make sure it is used in the right context. (Side note: This is different compared to a language like Java, which is strictly typed and method context is the compiler's responsibility. Perl operates similar to Python by using a Dynamic typing system. Haskell's You-Must-Be-Mad-Authoritarian style typing system is so strongly typed that your program won't compile even when you think it should, and it's usually because of a data type mix-up.)

>>> def hello():
...     print "hello"
... 
>>> hello()
hello

Python passes all values by reference. But that's not to say that you can change a value after it is passed. Data types in Python are put into two classes: mutable types (which can change) and immutable types (which cannot change):

Immutable types (which cannot change):
Numbers (including Integers, Booleans, Floating point, and Complex Numbers)
Strings (including regular Strings and Unicode Strings)
Tuples (which are essentially constant list)

Mutable Types (which can change):
List
Dictionaries (Python's name for associative arrays or hash tables)

Here's an example of the selection sort:

>>> def sort(list):
...     l = len(list)
...     for i in range(l):
...         min = i
...         for j in range(i+1,l):
...             if list[j] < list[min]:
...                 min = j
...         list[i], list[min] = list[min], list[i] # Swaps two variables.
... 
>>>
>>> a = [4,5,7,3,5,3,65,7,4,34,5,76,5,43,3,5,7]
>>> sort(a)
>>> a
[3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 7, 7, 7, 34, 43, 65, 76]

Here's an example of the quadratic equation problem to show how a method can return a list. It requires the math library to get the square root function.

>>> import math
>>> def quad(a, b, c):
...     s = b*b - 4 * a * c
...     if s < 0:
...         return []
...     if s == 0:
...         return [ -b / (2 * a) ]
...     sr = math.sqrt(s)
...     return [ (-b + sr) / (2 * a), (-b - sr) / (2 * a) ]
... 
>>> 
>>> 
>>> quad(3,1,-2)  # 3x^2 + x - 2, 2 solutions
[0.66666666666666663, -1.0]
>>> quad(2,4,2) # 2x^2 + 4x + 2, 1 solution
[-1]
>>> quad(6,-2,27) # 6x^2 - 2x + 27, 0 solutions
[]

Comments (0)

You don't have permission to comment on this page.