In Python, lists store multiple values in a single variable. To work with these values, you need to know how to access individual items, ranges of items, and how to check if a value exists in the list.
You can:
0) to access specific items.in keyword to check if an item exists in the list.0 for the first item.-1 for the last item.list[start:end].in to check if an item exists.? Indexing
list_name[index] – returns the item at the given index.
? Negative Indexing
list_name[-1] – last item, list_name[-2] – second last, and so on.
? Slicing
list_name[start:end] – returns items from start index up to (but not including) end index.
? Membership
item in list_name – returns True if the item exists in the list.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is in the list!")
fruits[0] → "apple" (first item).fruits[2] → "cherry" (third item).fruits[-1] → "cherry" (last item).fruits[-2] → "banana" (second last item).numbers[1:4] → [20, 30, 40] (indexes 1, 2, 3).numbers[:3] → [10, 20, 30] (start to index 2).numbers[3:] → [40, 50, 60] (index 3 to end)."banana" in fruits → True, so the message is printed.Notice how slicing always stops before the end index. Also, negative indexes are very handy when you only care about items near the end of the list.
in operator is great for quick membership checks.0.fruits, numbers) for readability."mango" is in a list of fruits.start and end values in slicing to see how the result changes.