Friday, July 25, 2014

Python programming Day 06

The append method modifies a list while the + operator creates a new list

>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None

>>> t3 = t1 + [4]
>>> print t3
[1, 2, 3, 4]

The below function doesn't delete the head of a list

def bad_delete_head(lis):
      lis = lis[1:]

The below function deletes the head of a list

def correct_delete_head(lis):
      return lis[1:] 

The correct_delete_head function leaves the original list unmodified.

>>> letters = ['a', 'b', 'c']
>>> rest = correct_delete_head(letters)
>>> print rest
['b', 'c']

Most list methods modify the argument and return None. This is the opposite of the string methods, which return a new string and leave the original alone.

References
Allen B. Downey, Think Python: How to Think Like a Computer Scientist,
http://www.greenteapress.com/thinkpython/html/index.html

No comments:

Post a Comment

Mounting USB drives in Windows Subsystem for Linux

Windows Subsystem for Linux can use (mount): SD card USB drives CD drives (CDFS) Network drives UNC paths Local storage / drives Drives form...