12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7. Generic operations. Question answers:• The + operator doesn’t work on different/mixed types (e.g., string + list, list+ tuple).• + doesn’t work for dictionaries, as they aren’t sequences.• The append method works only for lists, not strings, and keys works only ondictionaries. append assumes its target is mutable, since it’s an in-placeextension; strings are immutable.• Slicing and concatenation always return a new object of the same type as theobjects processed.>>> "x" + 1Traceback (innermost last):File "", line 1, in ?TypeError: illegal argument type for built-in operation>>>>>> {} + {}Traceback (innermost last):File "", line 1, in ?TypeError: bad operand type(s) for +>>>>>> [].append(9)>>> "".append('s')Traceback (innermost last):File "", line 1, in ?AttributeError: attribute-less object>>>>>> {}.keys( )[]>>> [].keys( )Traceback (innermost last):File "", line 1, in ?AttributeError: keys>>>>>> [][:][]>>> ""[:]''8. String indexing. Because strings are collections of one-character strings, everytime you index a string, you get back a string that can be indexed again.S[0][0][0][0][0] just keeps indexing the first character over and over. This generallydoesn’t work for lists (lists can hold arbitrary objects) unless the listcontains strings:>>> S = "spam">>> S[0][0][0][0][0]'s'>>> L = ['s', 'p']>>> L[0][0][0]'s'652 | Appendix B: Solutions to End-of-Part Exercises

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

Saved successfully!

Ooh no, something went wrong!