Working With Lists in Python - Deleting Elements
Working With Lists in Python - Deleting Elements
XI Science
Computer Science
What is a list?
Output:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item,
-2 refers to the second last item etc.
Example Output:
Print the last item of the list:
thislist = ["apple", "banana", "cherry"] cherry
print(thislist[-1])
Range of Indexes
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output:
Example
This example returns the items from the beginning to "orange":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output:
Example
This example returns the items from the beginning to "orange":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output:
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Output:
Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output:
To change the value of a specific item, we should refer the index number and assign
the new element.
For Example
Output:
Example
Print all items in the list, one by one:
Output:
apple
banana
cherry
Check if Item Exists
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output:
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
The pop() method removes the specified index, (or the last
item if index is not specified): ['apple', 'banana']
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Remove Item from a list
The pop() method removes the specified index, (or the last
item if index is not specified): ['apple', 'banana']
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)