0% found this document useful (0 votes)
2 views

Copy and Reversed Functions in Python (1)

The document explains key list operations in Python, including negative indexing, which allows access to list elements from the end. It also covers how to specify a range of indexes to return a new list, the importance of using the copy() method to duplicate lists, and methods for reversing a list using reverse() or slicing. Examples are provided for each operation to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Copy and Reversed Functions in Python (1)

The document explains key list operations in Python, including negative indexing, which allows access to list elements from the end. It also covers how to specify a range of indexes to return a new list, the importance of using the copy() method to duplicate lists, and methods for reversing a list using reverse() or slicing. Examples are provided for each operation to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

functions in python

Negative Indexing

Negative indexing means start from the end


-

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

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.

Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "m
ango"]
print(thislist[2:5])
Copy list

You cannot copy a list simply by typing list2 = list1,


because: list2 will only be a reference to
list1, and changes made in list1 will automatically also be made in list2.

Use the copy() method


You can use the built-in List method copy() to copy a 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]

# Create a new list that is a reversed list


# of 'a' using slicing
rev = a[::-1]

print(rev)

You might also like