Every day, we face this; you just need to remember.
GET
Get first value of list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
print(countries[0])
# Java
Get last value of list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
print(countries[-1])
# Python
Get the first 2 elements of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
print(countries[0:2])
# ['Java', 'C++']
Get the last 2 elements of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
print(countries[-2:])
# ['C#', 'Python']
Get every second element of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
print(countries[::2])
# ['Java', 'JavaScript', 'Python']
Get reverse list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.reverse()
print(countries)
# or
print(countries[::-1])
# ['Python', 'C#', 'JavaScript', 'C++', 'Java']
ADD
Add an element to the beginning of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.insert(0, 'Go')
print(countries)
# ['Go', 'Java', 'C++', 'JavaScript', 'C#', 'Python']
Add an element to the end of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.append('Ruby')
print(countries)
# ['Java', 'C++', 'JavaScript', 'C#', 'Python', 'Ruby']
Add two elements to the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.extend(['Go', 'Rust'])
print(countries)
# ['Java', 'C++', 'JavaScript', 'C#', 'Python', 'Go', 'Rust']
Append vs Extend
Note: append vs extend? Append - adds a list to a list. Extend - adds a list of values to a list.
Example:
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.append(['Go', 'Rust'])
print(countries)
# ['Java', 'C++', 'JavaScript', 'C#', 'Python', ['Go', 'Rust']]
REMOVE
Remove the last element of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.pop()
print(countries)
# ['Java', 'C++', 'JavaScript', 'C#']
Remove all occurrences of Python
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.remove('Python')
print(countries)
# ['Java', 'C++', 'JavaScript', 'C#']
Remove the first element of the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.pop(0)
print(countries)
# ['C++', 'JavaScript', 'C#', 'Python']
Remove the element at index 1
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.pop(1)
print(countries)
#['Java', 'JavaScript', 'C#', 'Python']
Remove all elements from the list
countries = ['Java', 'C++', 'JavaScript', 'C#', 'Python']
countries.clear()
print(countries)
# []
If I have omitted something, please add your variants in the comments and I will incorporate them into the article. Thank you for your attention.