Python tutorials > Data Structures > Lists > How to create/access list elements?
How to create/access list elements?
Creating a List
[]
. Inside the brackets, you can place any number of items separated by commas. These items can be of different data types (integers, strings, etc.). An empty list can be created using my_list = []
.
my_list = [1, 2, 3, 'apple', 'banana']
Accessing List Elements by Index
-1
refers to the last element, -2
to the second-to-last, etc.). Trying to access an index that is out of range (e.g., accessing index 10 in a list of length 5) will raise an IndexError
.
my_list = [10, 20, 30, 40, 50]
first_element = my_list[0] # Accesses the first element (10)
third_element = my_list[2] # Accesses the third element (30)
last_element = my_list[-1] # Accesses the last element (50)
print(f'First element: {first_element}')
print(f'Third element: {third_element}')
print(f'Last element: {last_element}')
List Slicing
my_list[start:end:step]
. start
is the index to start the slice (inclusive). end
is the index to end the slice (exclusive). step
is the increment between each element in the slice. If start
is omitted, it defaults to 0. If end
is omitted, it defaults to the end of the list. If step
is omitted, it defaults to 1.
my_list = [10, 20, 30, 40, 50, 60]
sub_list = my_list[1:4] # Creates a sub-list from index 1 up to (but not including) index 4 ([20, 30, 40])
start_from_beginning = my_list[:3] # Creates a sub-list from the beginning up to (but not including) index 3 ([10, 20, 30])
to_the_end = my_list[3:] # Creates a sub-list from index 3 to the end ([40, 50, 60])
all_elements = my_list[:] # Creates a copy of the entire list ([10, 20, 30, 40, 50, 60])
step_size = my_list[::2] # Creates a sub-list with a step size of 2 ([10, 30, 50])
reverse_list = my_list[::-1] # Reverse the list ([60, 50, 40, 30, 20, 10])
print(f'Sublist: {sub_list}')
print(f'Start from beginning: {start_from_beginning}')
print(f'To the end: {to_the_end}')
print(f'All elements: {all_elements}')
print(f'Step Size: {step_size}')
print(f'Reversed list: {reverse_list}')
Concepts Behind the Snippets
Real-Life Use Case Section
Best Practices
IndexError
when accessing list elements.
Interview Tip
When to Use Them
Memory Footprint
Alternatives
Pros
Cons
FAQ
-
What happens if I try to access an index that is out of range?
You will get anIndexError
. Make sure your index is within the valid range of indices for the list (0 to length of list - 1). -
Does slicing modify the original list?
No, slicing creates a new list containing the selected elements. The original list remains unchanged. -
Can I use negative indices to access elements from the end of the list?
Yes, negative indices are a convenient way to access elements from the end.my_list[-1]
refers to the last element,my_list[-2]
to the second-to-last, and so on.