1. List
- A list is a collection that is ordered and changeable. Allows duplicate members.
- Python Lists are similar to arrays in C.
- However, the list can contain data of different types.
- The items stored in the list are separated with a comma (,) and enclosed within square brackets [].
Examples
list = ["apple", "banana", "cherry"] #list of fruits
print(list)
list = ["apple", "banana", "cherry", "apple", "cherry"] #duplicate items
print(list)
print(len(list)) #len()...length of list
list1 = ["abc", 34, True, 40, "male"] #list of diff data types
mylist = ["apple", "banana", "cherry"]
print(type(mylist)) #type of list
print(list)
list = ["apple", "banana", "cherry", "apple", "cherry"] #duplicate items
print(list)
print(len(list)) #len()...length of list
list1 = ["abc", 34, True, 40, "male"] #list of diff data types
mylist = ["apple", "banana", "cherry"]
print(type(mylist)) #type of list
2. Python - Access List Items
List items are indexed and you can access them by referring to the index number
The first item has index 0.
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
3. Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
list = ["apple", "banana", "cherry"]
print(list[-1])
4. Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
5. Python - Change List Items
To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
6. Python - Add List Items
To add an item to the end of the list, use the append() method
a = ["apple", "banana", "cherry"]
a.append("orange")
print(a)
7. Python - Remove List Items
The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
The del keyword also removes the specified index
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
8. Python - Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
No comments:
Post a Comment