16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 2 ■ LISTS AND TUPLES 37<br />

>>> numbers[8:3:-1]<br />

[9, 8, 7, 6, 5]<br />

>>> numbers[10:0:-2]<br />

[10, 8, 6, 4, 2]<br />

>>> numbers[0:10:-2]<br />

[]<br />

>>> numbers[::-2]<br />

[10, 8, 6, 4, 2]<br />

>>> numbers[5::-2]<br />

[6, 4, 2]<br />

>>> numbers[:5:-2]<br />

[10, 8]<br />

Getting things right here can involve a bit of thinking. As you can see, the first limit (the<br />

leftmost) is still inclusive, while the second (the rightmost) is exclusive. When using a negative<br />

step size, you have <strong>to</strong> have a first limit (start index) that is higher than the second one. What<br />

may be a bit confusing is that when you leave the start and end indices implicit, <strong>Python</strong> does<br />

the “right thing” here; for a positive step size it moves from the beginning <strong>to</strong>ward the end, and<br />

for a negative step size it moves from the end <strong>to</strong>ward the beginning.<br />

Adding Sequences<br />

Sequences can be concatenated with the addition (plus) opera<strong>to</strong>r:<br />

>>> [1, 2, 3] + [4, 5, 6]<br />

[1, 2, 3, 4, 5, 6]<br />

>>> 'Hello, ' + 'world!'<br />

'Hello, world!'<br />

>>> [1, 2, 3] + 'world!'<br />

Traceback (innermost last):<br />

File "", line 1, in ?<br />

[1, 2, 3] + 'world!'<br />

TypeError: can only concatenate list (not "string") <strong>to</strong> list<br />

As you can see from the error message, you can’t concatenate a list and a string, although<br />

both are sequences. In general, you can only concatenate two sequences of the same kind.<br />

Multiplication<br />

Multiplying a sequence by a number x creates a new sequence where the original sequence is<br />

repeated x times:<br />

>>> 'python' * 5<br />

'pythonpythonpythonpythonpython'<br />

>>> [42] * 10<br />

[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!