Python Access Lists
Syntax
You can access elements in a Python list using indices, slices, or loops.
# Accessing elements by indexmy_list = [10, 20, 30, 40, 50]first_element = my_list[0] # 10last_element = my_list[-1] # 50
# Accessing a range of elements (slicing)sub_list = my_list[1:4] # [20, 30, 40]
# Iterating through a listfor item in my_list: print(item)Example
# Accessing specific elements and slicing a list of citiescities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
# Access the first and last citiesfirst_city = cities[0]last_city = cities[-1]print(f"The first city is {first_city}, and the last city is {last_city}.")
# Access a subset of the citiessubset = cities[1:4]print(f"A subset of cities: {subset}")