Lists
Lists in Python are versatile data structures that allow efficient manipulation and storage of a collection of items. Unlike basic data types like integers, floats, Booleans, and strings, lists can hold multiple items, which can be of different data types, all within a single variable.
Creating Lists
Lists are defined using square brackets [], with elements separated by commas. Each element occupies a position or index within the list.
# Example of a list of strings
fruits = ["apple", "banana", "cherry", "date"]
Accessing List Elements
- Indexing: Access elements by their position.
- Zero-based indexing: The first element is at index
0. - Negative indexing: The last element is at index
-1.
- Zero-based indexing: The first element is at index
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: date
- Slicing: Access a subset of the list.
- Syntax:
list[start:stop](excluding thestopindex).
- Syntax:
print(fruits[1:3]) # Output: ['banana', 'cherry']