How to Utilize Values in a List
To utilize values within a list, you use an index
that starts from 0.
The index of the first element is 0
, the second element is 1
, and it increases sequentially after that.
Negative indices count from the end: -1
is the last element, -2
the second-to-last, and so on.
fruits = ["Apple", "Banana", "Grape", "Cherry"]
# First element
first_fruit = fruits[0]
# "Apple"
print("first_fruit:", first_fruit)
# Second element
second_fruit = fruits[1]
# "Banana"
print("second_fruit:", second_fruit)
# Last element
last_fruit = fruits[-1]
# "Cherry"
print("last_fruit:", last_fruit)
Slicing to Retrieve a Portion of a List
To retrieve a portion of a list, we use slicing
. It is is a method that uses list indices to extract a specific range of elements.
To perform slicing, specify the start and end indices separated by a colon :
inside square brackets []
. For example, you can slice the fruits list using fruits[0:2]
.
The start index is included, while the end index is excluded. So, fruits[0:2]
returns the first and second elements of the list. The third element, fruits[2]
, is not included in the result.
fruits = ["Apple", "Banana", "Grape", "Cherry"]
# From the first element to the second element
first_two_fruits = fruits[0:2]
# fruits[2] is not included
print("first_two_fruits:", first_two_fruits)
# ['Apple', 'Banana']
Nested Lists
A nested list
is a list that contains other lists as its elements.
This allows you to represent complex data structures like multidimensional arrays or matrices.
# Create a 2D list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# First element of the nested list
print(nested_list[0])
# Output: [1, 2, 3]
# Specific element of a nested list
print(nested_list[0][1])
# Output: 2 (2nd element of the 1st list)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.