Copy and Reversed Functions in Python (1)
Copy and Reversed Functions in Python (1)
Negative Indexing
refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "m
ango"]
print(thislist[2:5])
Copy list
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Reversing a list items
To reverse a list in Python, two basic methods are commonly used,
• the built-in reverse() method and
• slicing with [::-1]. The reverse() method directly reverses the elements
of the list in place.
• a = [1, 2, 3, 4, 5]
• a.reverse()
• print(a) It updates the existing list without generating another one. This
method saves memory but changes the original list.
• Or slicing method
• a = [1, 2, 3, 4, 5]
• convert it back to a list
• rev = list(reversed(a))
• print(rev)
a = [1, 2, 3, 4, 5]
print(rev)