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.
The index of the last element is -1
, the second-to-last is -2
, decreasing sequentially.
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
.
Slicing is a technique that uses list indices to extract a desired portion.
To slice a list, specify the start and end indices separated by a colon :
inside the square brackets []
.
For example, you can slice the fruits
list with fruits[0:2]
.
The start index is included, but the end index is not.
For example, fruits[0:2]
extracts from the first element to the second element.
The third element, fruits[2]
, is not included in the result of the slice.
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.