Why is Python’s join() a STRING method, not a list method? *’.join(x):::’.join(x) Not: Why not? The argument can be any string-returning iterable: *’.join(‘abcde’)*’.join(str(x) for x in range(5))*’.join(open(‘myfile.txt’))
Want to reverse a sequence (string/list/tuple)? Use a 3-argument slice: This works because: – Empty start means “from the start”– Empty end means “through the end”– Step size of -1 means “go back 1 each time” This returns a new value, from s’s end to its start.
Python is all about consistency. For example, sequences (string/list/tuple) all support:
I recently received a question from a reader of my “Better developers” list. He asks: Is there any way to turn a str type into a list type? For example, I have a list of elements, and want to turn that element into a separate list. For example, if I have test = [‘a’, ‘b’,…
Let’s say you have a list in Python: >>> mylist = [10, 20, 30] You want to add something to that list. The most standard way to do this is with the “append” method, which adds its argument to the end of the list: >>> mylist.append(40) >>> print(mylist) [10, 20, 30, 40] But what if…
If you have children, then you probably remember them learning to walk, and then to read. If you’re like me, you were probably amazed by how long it took to do things that we don’t even think about. Things that we take for granted in our day-to-day lives, and which seem so obvious to us,…
I love Python’s “zip” function. I’m not sure just what it is about zip that I enjoy, but I have often found it to be quite useful. Before I describe what “zip” does, let me first show you an example: >>> s = ‘abc’ >>> t = (10, 20, 30) >>> zip(s,t) [(‘a’, 10), (‘b’,…
Bottom line: A nested list comprehension is just multiple “for” clauses in a single comprehension, read left to right, outermost first: [(x,y) for x in range(5) for y in range(5)]. Each additional “for” flattens the data by one more level, and every variable it defines is available to the output expression and to an optional…
My ebook, Practice Makes Python, will go on pre-sale one week from today. The book is a collection of 50 exercises that I have used and refined when training people in Python in the United States, Europe, Israel, and China. I have found these exercises to be useful in helping people to go beyond Python’s…
Bottom line: To turn a PostgreSQL array into rows, wrap the column in the UNNEST function: SELECT UNNEST(stuff) FROM foo. Each element of the array becomes its own row, which you can then join, filter, or feed into INTERSECT and UNION. Wrap the whole query in ARRAY(…) to pack the rows back into an array.…