Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. ## Tips, Tricks, Ways-of-doing-stuff
  2. ## with Lists in Python
  3.  
  4.  
  5. ########################################################################
  6.  
  7. # join() is a string method, but it can "join" a list's elements together,
  8. # BUT ONLY IF the elements are strings or can be first cast as strings.
  9. myList = ['apple', 'a', 'p', 'p', 'l', 'e']
  10. ''.join(myList)
  11. # results in:
  12. 'appleapple'
  13.  
  14. myOtherList = ['I', 'enjoy', 'spam']
  15. ' '.join(myOtherList)
  16. # results in:
  17. 'I enjoy spam'
  18.  
  19. ########################################################################
  20.  
  21. ## Assign elements of a list to separate variables
  22. myList = [1, 2, 3]
  23. x, y, z = myList
  24.  
  25. ########################################################################
  26.  
  27. ## Adding elements to lists:
  28. ## the differences between list.append(), list1 + list2, and list.extend()
  29.  
  30. list1 = [1, 2, 3]
  31. list2 = [4, 5, 6]
  32.  
  33. # append() mutates a list in place.
  34. # DO NOT assign this statement to a variable, you won't get a new list.
  35. # OK:
  36. list1.append(list2) #--> [1, 2, 3, [4, 5, 6]]
  37. # Not OK:
  38. list3 = list1.append(list2)
  39. list3 #--> NoneType
  40.  
  41. # the + operator creates a new list out of the objects on either side of the +,
  42. # as well as concatenates multiple lists' elements into a "flattened" 1D list.
  43. list3 = list1 + list2
  44. list3 #--> [1, 2, 3, 4, 5, 6]
  45.  
  46. # extend() mutates a list in place, like append, but unlike append (and like +),
  47. # extend() unpacks and therefore "flattens" its arg (a list or other iterable)
  48. # while also appending it to the first list. BE CAREFUL: extend will unpack ANY
  49. # iterable object, including strings.
  50. myList = [1, 2, 3]
  51. myStr = 'spam'
  52. # e.g.,
  53. myList.extend(['spam'])
  54. # myList --> [1, 2, 3, 'apple']
  55. # HOWEVER...
  56. myList.extend('spam')
  57. # myList --> [1, 2, 3, 'a', 'p', 'p', 'l', 'e'] # maybe not what was intended.
  58.  
  59. ########################################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement