Basic Operations on Lists
Once you have a list of integers, there are a number of basic operations you can perform on it. Here are some of the most common ones:
Accessing Elements
You can access individual elements in a list using their index. In Python, list indices start at 0, so the first element is at index 0, the second at index 1, and so on. For example:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) ## Output: 1
print(my_list[2]) ## Output: 3
Adding Elements
You can add new elements to a list using the append()
method or the +
operator. For example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) ## Output: [1, 2, 3, 4]
my_list = [1, 2, 3]
my_list = my_list + [4, 5]
print(my_list) ## Output: [1, 2, 3, 4, 5]
Removing Elements
You can remove elements from a list using the remove()
method or the del
keyword. For example:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) ## Output: [1, 2, 4, 5]
my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list) ## Output: [1, 2, 4, 5]
Sorting Elements
You can sort the elements in a list using the sort()
method or the sorted()
function. For example:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort()
print(my_list) ## Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_list = sorted(my_list)
print(sorted_list) ## Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
These are just a few of the basic operations you can perform on lists of integers in Python. In the next section, we'll explore some more advanced list manipulation techniques.