Python Developer - Python Lists - Access List Items | Tutorial 16
Автор: Professional Skill 2023
Загружено: 2025-10-04
Просмотров: 61
Описание:
Python - Access List Items
In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects. Similar to arrays, each element in a list corresponds to an index.
To access the values within a list, we need to use the square brackets "[]" notation and, specify the index of the elements we want to retrieve.
Accessing elements of a list is a common operation and can be done using different techniques. Below, we explore these methods in order of efficiency and their use cases. Indexing is the simplest and most direct way to access specific items in a list. Every item in a list has an index starting from 0.
1-Access Items
List items are indexed and you can access them by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
2-Negative Indexing
Negative indexing means start from the end -1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
3-Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
4-Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
5-Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: