I am new to python and was reading through some code for a Sublime Text plugin and came across some code I am not familiar with.
views = [v for v in sublime.active_window().views()]
it is the "[v for v" part that I don't understand. What in the heck is this piece of code doing?
Thanks in advance!
This is a list comprehension. It's a bit like an expression with an inline for loop, used to create a quick list on the fly. In this case, it's creating a shallow copy of the list returned by sublime.active_window().views()
.
List comprehensions really shine when you need to transform each value. For example, here's a quick list comprehension to get the first ten perfect squares:
[x*x for x in range(1,11)]