Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Tips, Tricks, Ways-of-doing-stuff
- ## with Lists in Python
- ########################################################################
- # join() is a string method, but it can "join" a list's elements together,
- # BUT ONLY IF the elements are strings or can be first cast as strings.
- myList = ['apple', 'a', 'p', 'p', 'l', 'e']
- ''.join(myList)
- # results in:
- 'appleapple'
- myOtherList = ['I', 'enjoy', 'spam']
- ' '.join(myOtherList)
- # results in:
- 'I enjoy spam'
- ########################################################################
- ## Assign elements of a list to separate variables
- myList = [1, 2, 3]
- x, y, z = myList
- ########################################################################
- ## Adding elements to lists:
- ## the differences between list.append(), list1 + list2, and list.extend()
- list1 = [1, 2, 3]
- list2 = [4, 5, 6]
- # append() mutates a list in place.
- # DO NOT assign this statement to a variable, you won't get a new list.
- # OK:
- list1.append(list2) #--> [1, 2, 3, [4, 5, 6]]
- # Not OK:
- list3 = list1.append(list2)
- list3 #--> NoneType
- # the + operator creates a new list out of the objects on either side of the +,
- # as well as concatenates multiple lists' elements into a "flattened" 1D list.
- list3 = list1 + list2
- list3 #--> [1, 2, 3, 4, 5, 6]
- # extend() mutates a list in place, like append, but unlike append (and like +),
- # extend() unpacks and therefore "flattens" its arg (a list or other iterable)
- # while also appending it to the first list. BE CAREFUL: extend will unpack ANY
- # iterable object, including strings.
- myList = [1, 2, 3]
- myStr = 'spam'
- # e.g.,
- myList.extend(['spam'])
- # myList --> [1, 2, 3, 'apple']
- # HOWEVER...
- myList.extend('spam')
- # myList --> [1, 2, 3, 'a', 'p', 'p', 'l', 'e'] # maybe not what was intended.
- ########################################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement