15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

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.

False<br />

>>><br />

>>> 'x' in mixup_list[1]<br />

True<br />

>>> num_list<br />

[[65535L, 2e+030, (76.45-1.3j)], -1.23, 16.0, -49]<br />

>>><br />

>>> -49 in num_list<br />

True<br />

>>><br />

>>> 34 in num_list<br />

False<br />

>>><br />

>>> [65535L, 2e+030, (76.45-1.3j)] in num_list<br />

True<br />

Note how 'x' is not a member of mixup_list. That is because 'x' itself is not actually a member of<br />

mixup_list. Rather, it is a member of mixup_uplist[1], which itself is a list. The membership operator is<br />

applicable in the same manner for tuples.<br />

Concatenation ( + )<br />

The concatenation operator allows us to join multiple lists together. Note in the examples below that<br />

there is a restriction of concatenating like objects. In other words, you can concatenate only objects of<br />

the same type. You cannot concatenate two different types even if both are sequences.<br />

>>> num_list = [43, -1.23, -2, 6.19e5]<br />

>>> str_list = ['jack', 'jumped', 'over', 'candlestick']<br />

>>> mixup_list = [4.0, [1, 'x'], 'beef', -1.9+6j]<br />

>>><br />

>>> num_list + mixup_list<br />

[43, -1.23, -2, 619000.0, 4.0, [1, 'x'], 'beef', (-1.9+6j)]<br />

>>><br />

>>> str_list + num_list<br />

['jack', 'jumped', 'over', 'candlestick', 43, -1.23, -2, 619000.0]<br />

As we will discover in Section 6.13, starting in <strong>Python</strong> 1.5.2, you can use the extend() method in place<br />

of the concatenation operator to append the contents of a list to another. Using extend() is<br />

advantageous over concatenation because it actually appends the elements of the new list to the<br />

original, rather than creating a new list from scratch like + does. extend() is also the method used by the<br />

augmented assignment or in-place concatenation operator (+=), which debuted in <strong>Python</strong> 2.0.<br />

We would also like to point out that the concatenation operator does not facilitate adding individual<br />

elements to a list. The upcoming example illustrates a case where attempting to add a new item to the<br />

list results in failure.<br />

>>> num_list + 'new item'

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

Saved successfully!

Ooh no, something went wrong!