I am out of trial and error again Lists
Ian Kelly
ian.g.kelly at gmail.com
Sat Oct 25 10:17:06 EDT 2014
On Sat, Oct 25, 2014 at 12:46 AM, Larry Hudson
<orgnut at yahoo.com.dmarc.invalid> wrote:
>> name="123-xyz-abc"
>> for x in name:
>> if x in range(10):
>
> x is a character (a one-element string). range(10) is a list of ints. A
> string will never match an int. BTW, as it is used here, range(10) is for
> Py2, for Py3 it needs to be list(range(10)).
The last comment is incorrect. You can do membership tests on a Python
3 range object:
>>> range(2, 4)
range(2, 4)
>>> for i in range(5):
... print(i, i in range(2, 4))
...
0 False
1 False
2 True
3 True
4 False
You can also index them:
>>> range(50, 100)[37]
87
slice them:
>>> range(0, 100, 2)[:25]
range(0, 50, 2)
get their length:
>>> len(range(25, 75))
50
search them:
>>> range(25, 75).index(45)
20
and generally do most operations that you would expect to be able to
do with an immutable sequence type, with the exceptions of
concatenation and multiplication. And as I observed elsewhere in the
thread, such operations are often more efficient on range objects than
by constructing and operating on the equivalent lists.
More information about the Python-list
mailing list