SCOUG-Programming Mailing List Archives
Return to [ 24 |
April |
2005 ]
<< Previous Message <<
Content Type: text/plain
I was working on several examples of Python lists and list operations when I ran across the lesson
that follows. If more specific examples are desired let me know.
An element in a Python list may be any Python object including another list, a dictionary, or even a
user designed class object.
The lines beginning with >>> are inputs to the Python interpreter. The line following is the
interpreter output.
The numbers at the end of some lines refer to numbered notes that follow the code snippet.
The whole thing looks much better in the original HTML. See:
http://www.andamooka.org/reader.pl?pgid=diveinodbchelper_list
I might point out that Python lists can simulate a LIFO list by the commands list.append(element)
and x = list.pop(). But you do have to think backwards (if, indeed, you even care how the list
works) because list.append does exactly what it means. It tacks an element onto the end of the
list. list.pop pops the last element from the list. Not what you would expect. I spent a lot of
time figuring that one out. Then again, if all you care about is that it work, it works.
A FIFO list is simulated by list.insert(0, element) and list.pop(). list.insert(0, element) will
insert the element into position 0 which is the very first position in the list. list.pop() still
pops the last element. As elements are popped off the list, eventually the erstwhile 0th element
works it way to the end of the list and gets popped off.
Sheridan
1.8. Lists 101
Lists are Python's workhorse datatype. If your only experience with lists is arrays in Visual Basic
or Lists in Java, brace yourself for Python lists.
Example 1.13. Defining a list
>>> li = ["a", "b", "mpilgrim", "z", "example"] 1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[0] 2
'a'
>>> li[4] 3
'example'
1 First, we define a list of 5 elements. Note that they retain their original order. This is not an
accident. A list is an ordered set of elements enclosed in square brackets.
2 A list can be used like a zero-based array. The first element of any non-empty list is always li[0].
3 The last element of this 5-element list is li[4], because lists are always zero-based.
Example 1.14. Negative list indices
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] 1
'example'
>>> li[-3] 2
'mpilgrim'
1 A negative index accesses elements from the end of the list counting backwards. The last element
of any non-empty list is always li[-1].
2 If negative indices are confusing to you, think of it this way: li[n] == li[n - len(li)]. So in
this list, li[2] == li[2 - 5] == li[-3].
Example 1.15. Slicing a list
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3] 1
['b', 'mpilgrim']
>>> li[1:-1] 2
['b', 'mpilgrim', 'z']
>>> li[0:3] 3
['a', 'b', 'mpilgrim']
1 You can get a subset of a list, called a “slice”, by specifying 2 indices. The return value is a
new list containing all the elements of the list, in order, starting with the first slice index (in
this case li[1]), up to but not including the second slice index (in this case li[3]).
2 Slicing works if one or both of the slice indices is negative. If it helps, you can think of it
this way: reading the list from left to right, the first slice index specifies the first element you
want, and the second slice index specifies the first element you don't want. The return value is
everything in between.
3 Lists are zero-based, so li[0:3] returns the first three elements of the list, starting at li[0],
up to but not including li[3].
Example 1.16. Slicing shorthand
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[:3] 1
['a', 'b', 'mpilgrim']
>>> li[3:] 2
['z', 'example']
>>> li[:] 3
['a', 'b', 'mpilgrim', 'z', 'example']
1 If either of the slice indices is 0, you can leave it out, and 0 is implied. So li[:3] is the
same as li[0:3] from the previous example.
2 Note the symmetry here. In this 5-element list, li[:3] returns the first 3 elements, and li[3:]
returns the last 2 elements. In fact, li[:n] will always return the first n elements, and li[n:]
will return the rest.
3 If both slice indices are left out, all elements of the list are included. But this is not the
same as the original li list; it is a new list that happens to have all the same elements. li[:] is
a shorthand for making a complete copy of a list.
Example 1.17. Adding elements to a list
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new") 1
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new") 2
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"]) 3
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
1 append adds a single element to the end of the list.
2 insert inserts a single element into a list. The numeric argument is the index of the first
element that gets bumped out of position. Note that list elements do not have to be unique; there
are now 2 separate elements with the value new, li[2] and li[6].
3 extend concatenates lists. Note that you do not call extend with multiple arguments; you call it
with one argument, a list. In this case, that list has two elements.
Example 1.18. Searching a list
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example") 1
5
>>> li.index("new") 2
2
>>> li.index("c") 3
Traceback (innermost last):
File "", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li 4
0
1 index finds the first occurrence of a value in the list and returns the index.
2 index finds the first occurrence of a value in the list. In this case, new occurs twice in the
list, in li[2] and li[6], but index will only return the first index, 2.
3 If the value is not found in the list, Python raises an exception. This is notably different from
most languages, which will return some invalid index. While this may seem annoying, it is a Good
Thing™, because it means your program will crash at the source of the problem, rather than later on
when you try to use the invalid index.
4 To test whether a value is in the list, use in, which returns 1 if the value is found or 0 if it
is not.
Note: There is no boolean datatype in Python. In a boolean context (like an if statement), 0 is
false and all other numbers are true. This extends to other datatypes, too. An empty string (""), an
empty list ([]), and an empty dictionary ({}) are all false; all other strings, lists, and
dictionaries are true.
[Ed. note: Python 3.4 + does have True and False (caps required) to make reading/writing boolean
constructs more intuitive.]
Example 1.19. Removing elements from a list
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.remove("z") 1
>>> li
['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("new") 2
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("c") 3
Traceback (innermost last):
File "", line 1, in ?
ValueError: list.remove(x): x not in list
>>> li.pop() 4
'elements'
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
1 remove removes the first occurrence of a value from a list.
2 remove removes only the first occurrence of a value. In this case, new appeared twice in the
list, but li.remove("new") only removed the first occurrence.
3 If the value is not found in the list, Python raises an exception. This mirrors the behavior of
the index method.
4 pop is an interesting beast. It does two things: it removes the last element of the list, and it
returns the value that it removed. Note that this is different from li[-1], which returns a value
but does not change the list, and different from li.remove(value), which changes the list but does
not return a value.
=====================================================
To unsubscribe from this list, send an email message
to "steward@scoug.com". In the body of the message,
put the command "unsubscribe scoug-programming".
For problems, contact the list owner at
"postmaster@scoug.com".
=====================================================
<< Previous Message <<
Return to [ 24 |
April |
2005 ]
The Southern California OS/2 User Group
P.O. Box 26904
Santa Ana, CA 92799-6904, USA
Copyright 2001 the Southern California OS/2 User Group. ALL RIGHTS
RESERVED.
SCOUG, Warp Expo West, and Warpfest are trademarks of the Southern California OS/2 User Group.
OS/2, Workplace Shell, and IBM are registered trademarks of International
Business Machines Corporation.
All other trademarks remain the property of their respective owners.
|