When tabs are created or closed, they are added/removed from the list.

Examples

Switching to the last opened tab.

In WebDriver, a link click that results in a new tab opening places the newly opened tab at the end of a list.

This list is accessible through calling driver.window_handles. You can easily access the most recently opened tab by calling driver.window_handles[-1].

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://example.com/")
# Find the object to interact with.
driver.find_element_by_class_name("foo").click()
# New tabs will be the last object in window_handles
driver.switch_to.window(driver.window_handles[-1])
# close the tab
driver.close()
# switch to the main window
driver.switch_to.window(driver.window_handles[0])