- Programmers can sort lists with the use of a built-in "sort()" method. The sort method called with no argument sorts the current list in ascending order. Using the "reverse" keyword will sort the list in descending order.
Take "example_list" as an example of a Python list:
>>>example_list.sort()
>>>example_list
[1, 2, 3, 4, 5, 7]
>>>example_list.sort(reverse=True)
>>>example_list
[7, 5, 4, 3, 2, 1] - Lists aso have methods to add elements to the end of the list. The "append()" method takes an item and adds it to the end of the list. The similar method "extend()" performs the same operation, but rather than a single element, "extend()" adds another list onto the end of the list. For example:
>>>example_list.append(10)
>>>example_list
[1, 2, 3, 4, 5, 7, 10]
>>>example_list.extend([11, 12, 13])
>>>example_list
[1, 2, 3, 4, 5, 7, 10, 11, 12, 13] - Programmers can also insert elements into and remove elements from arbitrary locations in the list (as long as the locations exist). The "insert()" method can insert an element into the list, and moves items in the list to accommodate the new item. The "remove()" method does the reverse: It removes the first instance of a value and rearranges the list to fill the empty index. Note: Python uses zero-based numbering, meaning the first element of a list (or any collection of data in Python) is assigned the index 0, the second element is assigned the index 1, and so on.
For example:
>>>example_list.insert(1, 17)
>>>example_list
[1, 17, 2, 3, 4, 5, 7, 10, 11, 12, 13]
>>>example_list.remove(2)
>>>example_list
[1, 17, 3, 4, 5, 7, 10, 11, 12, 13]
This example inserted the number 17 at the index 1 position, then removed the first instance of the number 2. - The "pop()" method, called without an argument, always returns and removes the final element in the list. With this method, a list can mimic a stack data structure. A stack follows the Last In, First Out pattern, in which the last value added in the list is always returned first:
>>>example_list.append(14)
>>>example_list
[1, 17, 3, 4, 5, 7, 10, 11, 12, 13, 14]
>>>example_list.pop()
[1, 17, 3, 4, 5, 7, 10, 11, 12] - A Queue follows the First In, First Out approach. This example uses the pop method with a single argument, which returns and removes the value at the given index:
>>>example_list.insert(0, 12)
>>>example_list
[12, 1, 17, 3, 4, 5, 7, 10, 11, 12]
>>>example_list.pop(0)
>>>example_list
[1, 17, 3, 4, 5, 7, 10, 11, 12]
previous post
next post