Creating Lists
A Python list is created by enclosing a comma-separated sequence of items within square brackets []
. Lists can contain elements of different data types.
Python
# Empty list
my_list = []
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "cherry"]
# List with mixed data types
mixed_list = [10, "hello", True, 3.14]
Accessing List Elements
You can access individual elements in a list using their index. Python uses zero-based indexing, meaning the first element has an index of 0.
Python
fruits = ["apple", "banana", "cherry"]
# Accessing the first element
first_fruit = fruits[0] # Output: apple
# Accessing the last element
last_fruit = fruits[-1] # Output: cherry
Slicing Lists
You can access a portion of a list using slicing. The syntax is list[start:end:step]
.
Python
numbers = [0, 1, 2, 3, 4, 5]
# Slice from index 1 to 4 (exclusive)
sublist = numbers[1:4] # Output: [1, 2, 3]
Creating and Accessing Lists
Important Points
- Lists are mutable, meaning you can change their contents after creation.
- Negative indices can be used to access elements from the end of the list.
- The
len()
function returns the number of elements in a list.
How do you create an empty list?
Use empty square brackets []
.
How do you access the first element of a list?
Use index 0, e.g., my_list[0]
.
How do you access the last element of a list?
Use negative indexing, e.g., my_list[-1]
.
What is slicing?
Slicing extracts a sublist from a list using start:end:step
notation.
Can a list contain different data types?
Yes, a list can contain elements of different data types.
Are lists mutable or immutable?
Lists are mutable, meaning their contents can be changed after creation.