DiveIntoPython(一)first program
英文书地址
http://diveintopython3.org/
下载得到PDF版本
http://diveintopython3.org/d/diveintopython3-pdf-r860-2010-01-13.zip
解开压缩得到文件diveintopython3-r860.pdf和很多example.
python本身的官方文档
http://docs.python.org/3.1/
以上是版本python3,后来再使用中发现google app engine和django都还没有支持到python3,所以我本机安装的python2.6.4,所以决定先从小版本看起。
英文书地址:
http://diveintopython.org/toc/index.html
chapter 1. Installing Python
1.1 介绍了两种方式下载python
1如果要最新版本,请下载官方版本,下载地址:http://www.python.org/
得到文件python-2.6.4.msi,双击安装
2比较实用,笔者推荐activePython,下载地址:http://www.activestate.com/activepython/downloads/
得到文件ActivePython-2.6.4.10-win32-x86.msi,双击安装
1.2 The Interactive Shell
An interactive shell can evaluate arbitrary statements and expressions.This is extremely useful for debugging,quick hacking and testing.
chapter 2.Your First Python Program
odbchelper.py in examples:
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
the output of odbchelper.py will look like this:
pwd=secret;database=master;uid=sa;server=mpilgrim
2.2 Declaring Function
def buildConnectionString(params):
python do not specify the type about return value and arguments.
2.2.2 How Python's Datatypes Compare to Other Programming Languages
statically typed language
A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language
A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language
A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language
A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.
2.3.Documenting Functions
def buildConnectString(params):
""" Build a connection string from a dictionary of parameters.
Return string """
Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.
2.4 Everything Is an Object
I type follow commands in my interactive shell:
>>> import odbchelper
>>> params = {"tt1":"tt1"}
>>> print odbchelper.buildConnectionString(params)
tt1=tt1
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary
Returns string.
2.4.1 The Import Search Path:
>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info', 'E:\\book\\opensource\\python\\diveintopython-5.4\\py']
You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.
2.4.2 What's an Object
All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.
everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
2.5 Indenting Code indent [in'dent, 'indent] n. 凹痕;订货单;契约;缩进 vt. 缩排
Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords.
bracket ['brækit] n. 支架;括号;墙上凸出的托架
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.
2.6 Testing Modules
Modules are objects, and all modules have a built-in attribute __name__ and __doc__.
Chapter 3 . Native Datatypes
3.1 Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
A dictionary in Python is like an instance of the Hashtable class in Java.
3.1.1. Defining Dictionaries
example:
>>> d = {"server":"mpilogrim","database":"master"}
>>> d
{'database': 'master', 'server': 'mpilogrim'}
>>> d["server"]
'mpilogrim'
>>> d["database"]
'master'
>>> d["ccc"]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'ccc'
the whole set of elements is enclosed in curly braces.And you can get values by key, but you can't get keys by value.
3.1.2 Modifying Dictionaries
>>> d["database"] = "pubs"
>>> d
{'database': 'pubs', 'server': 'mpilogrim'}
>>> d["uid"] = "sillycat"
>>> d
{'database': 'pubs', 'uid': 'sillycat', 'server': 'mpilogrim'}
You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.
examples:
>>> d["key"] = "other value"
>>> d
{'key': 'other value'}
>>> d["Key"] = "third value"
>>> d
{'Key': 'third value', 'key': 'other value'}
examples:
>>> d = {}
>>> d
{}
>>> d["retrycount"] = 3
>>> d
{'retrycount': 3}
>>> d[42] = "douglas"
>>> d
{'retrycount': 3, 42: 'douglas'}
Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed
Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
3.1.3 Deleting Items From Dictionaries
examples:
>>> d
{'retrycount': 3, 42: 'douglas'}
>>> del d[42]
>>> d
{'retrycount': 3}
>>> d.clear()
>>> d
{}
del lets you delete individual items from a dictionary by key.
clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.
3.2 Introducing Lists
Lists are Python's workhorse datatype.A list in Python is much more than an array in Java.A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.
3.2.1 Defining Lists
examples:
>>> li = ["a","b","mpilgrim","zt","hha"]
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[0]
'a'
>>> li[4]
'hha'
First, you define a list of five 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.
A list can be used like a zero-based array. The first element of any non-empty list is always li[0].
Negative List Indices
indice n. 指数;标记体 string indice: 字符串索引
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[-1]
'hha'
>>> li[-3]
'mpilgrim'
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].
Slicing a List
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[1:3]
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'zt']
>>> li[0:2]
['a', 'b']
You can get a subset of a list, called a “slice”, by specifying two 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]).
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.
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].
Slicing Shorthand shorthand ['ʃɔ:thænd] n. 速记;速记法
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:]
['zt', 'hha']
>>> li[:]
['a', 'b', 'mpilgrim', 'zt', 'hha']
If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3]
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements
Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.
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 shorthand for making a complete copy of a list.
3.2.2 Adding Elements to Lists
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.insert(2,"new2")
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.extend(["two","elements"])
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new', 'two', 'elements']
append adds a single element to the end of the list.
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 need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
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.
The Difference between extend and append
examples:
>>> li = ["a","b","c"]
>>> li.extend(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)
6
>>> li[-1]
'f'
>>> li.append(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> len(li)
7
>>> li[-1]
['d', 'e', 'f']
Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.
On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.
3.2.3 Searching Lists
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.index("b")
1
>>> li.index("f")
5
>>> li.index("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> "test" in li
False
index finds the first occurrence of a value in the list and returns the index.
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.
To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.
3.2.4 Deleting List Elements
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("b")
>>> li
['a', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> li.pop()
['d', 'e', 'f']
>>> li
['a', 'c', 'd', 'e', 'f']
remove removes the first occurrence of a value from a list.
If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.
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.
3.2.5 Usinig List Operators
examples:
>>> li = ["a","b",'mpigra']
>>> li = li + ['example','new']
>>> li
['a', 'b', 'mpigra', 'example', 'new']
>>> li +=['two']
>>> li
['a', 'b', 'mpigra', 'example', 'new', 'two']
>>> li = [1,2]*3
>>> li
[1, 2, 1, 2, 1, 2]
Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.
The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.
英文书地址
http://diveintopython3.org/
下载得到PDF版本
http://diveintopython3.org/d/diveintopython3-pdf-r860-2010-01-13.zip
解开压缩得到文件diveintopython3-r860.pdf和很多example.
python本身的官方文档
http://docs.python.org/3.1/
以上是版本python3,后来再使用中发现google app engine和django都还没有支持到python3,所以我本机安装的python2.6.4,所以决定先从小版本看起。
英文书地址:
http://diveintopython.org/toc/index.html
chapter 1. Installing Python
1.1 介绍了两种方式下载python
1如果要最新版本,请下载官方版本,下载地址:http://www.python.org/
得到文件python-2.6.4.msi,双击安装
2比较实用,笔者推荐activePython,下载地址:http://www.activestate.com/activepython/downloads/
得到文件ActivePython-2.6.4.10-win32-x86.msi,双击安装
1.2 The Interactive Shell
An interactive shell can evaluate arbitrary statements and expressions.This is extremely useful for debugging,quick hacking and testing.
chapter 2.Your First Python Program
odbchelper.py in examples:
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
the output of odbchelper.py will look like this:
pwd=secret;database=master;uid=sa;server=mpilgrim
2.2 Declaring Function
def buildConnectionString(params):
python do not specify the type about return value and arguments.
2.2.2 How Python's Datatypes Compare to Other Programming Languages
statically typed language
A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language
A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language
A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language
A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.
2.3.Documenting Functions
def buildConnectString(params):
""" Build a connection string from a dictionary of parameters.
Return string """
Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.
2.4 Everything Is an Object
I type follow commands in my interactive shell:
>>> import odbchelper
>>> params = {"tt1":"tt1"}
>>> print odbchelper.buildConnectionString(params)
tt1=tt1
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary
Returns string.
2.4.1 The Import Search Path:
>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info', 'E:\\book\\opensource\\python\\diveintopython-5.4\\py']
You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.
2.4.2 What's an Object
All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.
everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
2.5 Indenting Code indent [in'dent, 'indent] n. 凹痕;订货单;契约;缩进 vt. 缩排
Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords.
bracket ['brækit] n. 支架;括号;墙上凸出的托架
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.
2.6 Testing Modules
Modules are objects, and all modules have a built-in attribute __name__ and __doc__.
Chapter 3 . Native Datatypes
3.1 Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
A dictionary in Python is like an instance of the Hashtable class in Java.
3.1.1. Defining Dictionaries
example:
>>> d = {"server":"mpilogrim","database":"master"}
>>> d
{'database': 'master', 'server': 'mpilogrim'}
>>> d["server"]
'mpilogrim'
>>> d["database"]
'master'
>>> d["ccc"]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'ccc'
the whole set of elements is enclosed in curly braces.And you can get values by key, but you can't get keys by value.
3.1.2 Modifying Dictionaries
>>> d["database"] = "pubs"
>>> d
{'database': 'pubs', 'server': 'mpilogrim'}
>>> d["uid"] = "sillycat"
>>> d
{'database': 'pubs', 'uid': 'sillycat', 'server': 'mpilogrim'}
You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.
examples:
>>> d["key"] = "other value"
>>> d
{'key': 'other value'}
>>> d["Key"] = "third value"
>>> d
{'Key': 'third value', 'key': 'other value'}
examples:
>>> d = {}
>>> d
{}
>>> d["retrycount"] = 3
>>> d
{'retrycount': 3}
>>> d[42] = "douglas"
>>> d
{'retrycount': 3, 42: 'douglas'}
Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed
Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
3.1.3 Deleting Items From Dictionaries
examples:
>>> d
{'retrycount': 3, 42: 'douglas'}
>>> del d[42]
>>> d
{'retrycount': 3}
>>> d.clear()
>>> d
{}
del lets you delete individual items from a dictionary by key.
clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.
3.2 Introducing Lists
Lists are Python's workhorse datatype.A list in Python is much more than an array in Java.A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.
3.2.1 Defining Lists
examples:
>>> li = ["a","b","mpilgrim","zt","hha"]
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[0]
'a'
>>> li[4]
'hha'
First, you define a list of five 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.
A list can be used like a zero-based array. The first element of any non-empty list is always li[0].
Negative List Indices
indice n. 指数;标记体 string indice: 字符串索引
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[-1]
'hha'
>>> li[-3]
'mpilgrim'
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].
Slicing a List
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[1:3]
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'zt']
>>> li[0:2]
['a', 'b']
You can get a subset of a list, called a “slice”, by specifying two 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]).
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.
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].
Slicing Shorthand shorthand ['ʃɔ:thænd] n. 速记;速记法
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:]
['zt', 'hha']
>>> li[:]
['a', 'b', 'mpilgrim', 'zt', 'hha']
If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3]
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements
Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.
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 shorthand for making a complete copy of a list.
3.2.2 Adding Elements to Lists
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.insert(2,"new2")
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.extend(["two","elements"])
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new', 'two', 'elements']
append adds a single element to the end of the list.
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 need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
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.
The Difference between extend and append
examples:
>>> li = ["a","b","c"]
>>> li.extend(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)
6
>>> li[-1]
'f'
>>> li.append(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> len(li)
7
>>> li[-1]
['d', 'e', 'f']
Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.
On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.
3.2.3 Searching Lists
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.index("b")
1
>>> li.index("f")
5
>>> li.index("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> "test" in li
False
index finds the first occurrence of a value in the list and returns the index.
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.
To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.
3.2.4 Deleting List Elements
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("b")
>>> li
['a', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> li.pop()
['d', 'e', 'f']
>>> li
['a', 'c', 'd', 'e', 'f']
remove removes the first occurrence of a value from a list.
If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.
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.
3.2.5 Usinig List Operators
examples:
>>> li = ["a","b",'mpigra']
>>> li = li + ['example','new']
>>> li
['a', 'b', 'mpigra', 'example', 'new']
>>> li +=['two']
>>> li
['a', 'b', 'mpigra', 'example', 'new', 'two']
>>> li = [1,2]*3
>>> li
[1, 2, 1, 2, 1, 2]
Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.
The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.