Here is an example of the same approach with multiple levels:
levels = [0, 1, 2, 3]
cnt = plt.contour(x, y, f(X, Y), levels)
for level, contour in zip(levels, cnt.collections):
contour.set_label('level {level}')
plt.legend(bbox_to_anchor=[1.01, 1], loc='upper left')
plt.tight_layout()
plt.show()