Bài trước: Python căn bản (14): Python Lists (cont.1)
[Từ điển]
15. Python Lists (cont.2)
15.1 Add List Items
Append Items
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)
Extend List
To append elements from another list to the current list, use the extend() method.
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
The elements will be added to the end of the list.
Add Any Iterable
The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
Example
Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
15.2 Remove List Items
Remove Specified Item
The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
If there are more than one item with the specified value, the remove() method removes the first occurrence.
Example
Remove the first occurrence of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
Remove Specified Index
The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del keyword also removes the specified index.
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
15.3 Loop Lists
Loop Through a List
You can loop through the list items by using a for loop.
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is [0, 1, 2].
Using a While Loop
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index numbers:
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists.
Example
A shorthand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
15.4 Exercise
1. What will be the result of the following syntax:
mylist = ['apple', 'banana', 'cherry']
mylist.insert(0, 'orange')
print(mylist[1])
A. apple
B. banana
C. cherry
D. orange
2. What is a List method for removing list items?
A. pop()
B. push()
C. delete()
D.clear()
3. Insert the missing part of the while loop below to loop through the items of a list.
mylist = ['apple', 'banana', 'cherry']
i = 0
_____i < ______(mylist):
print(mylist[i])
i = i + 1
A. while, len
B. While, Len
C. white, length
D. white, len
4. What is the correct syntax for looping through the items of a list?
A. print(x) for x in ['apple', 'banana', 'cherry']
B. [print(x) for x in ['apple', 'banana', 'cherry']]
C. for x in ['apple', 'banana', 'cherry'] print(x)
D. for x in ('apple', 'banana', 'cherry') print(x)
5. Write a Python program, allow user input length of list (n), items of list, data type of item is number. Using the loop to input items of the list. Then turn every item of the list into its square.
Input:
Enter the length of the list: 5
Enter item 1: 1
Enter item 2: 2
Enter item 3: 3
Enter item 4: 4
Enter item 5: 5
Expected Output:
[1, 4, 9, 16, 25]
-----
The answer hints:
1(A), 2(A), 3(A), 4(B)
5. Write a Python program, allow user input length of list (n), items of list, data type of item is number. Using the loop to input items of the list. Then turn every item of the list into its square.
Input:
Enter the length of the list: 5
Enter item 1: 1
Enter item 2: 2
Enter item 3: 3
Enter item 4: 4
Enter item 5: 5
Expected Output:
[1, 4, 9, 16, 25]
[code15_5.py]
# Get the length of the list from the user
n = int(input("Enter
the length of the list: "))
# Create an empty list to store the input items
myList = []
# Loop to get the items from the user
for i in range(n):
item
= int(input(f"Enter item {i+1}: "))
myList.append(item)
# Create an empty list to store result list
result = []
# calculate square of each item and add to the result list
for i in myList:
result.append(i
* i)
# Print the result list
Cập nhật: 30/10/2024
Bài sau: Python căn bản (16): Python Lists (cont.3)
-----
[Nội dung tham khảo từ w3schools, pynative và Internet]
Bạn muốn học Python căn bản tại Đà Lạt, liên hệ