Python căn bản (15): Python Lists (cont.2)

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

print("Result list:", result)
-----

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ệ

Python căn bản (14): Python Lists (cont.1)

Bài trước: Python căn bản (13): Python Lists

[Từ điển]

-----

14. Python Lists (cont.1)

14.1 Access List Items

Access Items

List items are indexed and you can access them by referring to the index number.

Example

Print the second item of the list.

thislist = ["apple", "banana", "cherry"]

print(thislist[1])

Note: The first item has index 0.

Negative Indexing

Negative indexing means start from the end

-1 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", "mango"]

print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to, but NOT including, "kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

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" to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list.

Example

This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

Check if Item Exists

To determine if a specified item is present in a list use the in keyword.

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")

14.2 Change Item Value

To change the value of a specific item, refer to the index number.

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

print(thislist)

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values.

Example

Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

thislist[1:3] = ["blackcurrant", "watermelon"]

print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.

Example

Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]

thislist[1:2] = ["blackcurrant", "watermelon"]

print(thislist)

Note: The length of the list will change when the number of items inserted does not match the number of items replaced.

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.

Example

Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]

thislist[1:3] = ["watermelon"]

print(thislist)

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

The insert() method inserts an item at the specified index.

Example

Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]

thislist.insert(2, "watermelon")

print(thislist)

Note: As a result of the example above, the list will now contain 4 items.

14.3 Exercise

1. What will be the result of the following code:

mylist = ['apple', 'banana', 'cherry']

print(mylist[-1])

A. apple

B. banana

C. -1

D. cherry

2. Print the second item in the fruits list.

fruits = ["apple", "banana", "cherry"]

print(_______)

A. fruits[0]

B. fruits[1]

C. fruits[2]

D. fruits[-1]

3. What will be the result of the following code:

mylist = ['apple', 'banana', 'cherry', 'orange', 'kiwi']

print(mylist[1:4])

A. ['banana', 'cherry', 'orange']

B. ['banana', 'cherry', 'orange', 'kiwi']

C. ['cherry', 'orange', 'kiwi']

D. [1:4]

4. Use a range of indexes to print the third, fourth, and fifth item in the list.

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(fruits[______])

A. 3:5

B. 2:5

C. 2:4

D. 3:6

5. What will be the result of the following code:

mylist = ['apple', 'banana', 'cherry']

mylist[0] = 'kiwi'

print(mylist[1])

A. banana

B. cherry

C. apple

D. kiwi

6. What will be the result of the following code:

mylist = ['apple', 'banana', 'cherry']

mylist[1:2] = ['kiwi', 'mango']

print(mylist[2])

A. kiwi

B. mango

C. banana

D. cherry

7. Write a Python program to create a list to store student’s information, including: name, age, gender, GPA. Print the student’s information out following this pattern:

Information of Student:

[1] Name: Teo

[2] Age: 16

[3] Gender: male

[4] GPA: 3.0

-----

The answer hints:

1(D), 2(B), 3(A), 4(B), 5(A), 6(B)

7. Write a Python program to create a list to store student’s information, including: name, age, gender, GPA. Print the student’s information out following this pattern:

Information of Student:

[1] Name: Teo

[2] Age: 16

[3] Gender: male

[4] GPA: 3.0

[code14_7.py]

# Create a list to store student information

studentInfo = ["Teo", 16, "male", 3.0]

 

# Print the student's information

print("Information of Student:")

print(f"[1] Name: {studentInfo[0]}")

print(f"[2] Age: {studentInfo[1]}")

print(f"[3] Gender: {studentInfo[2]}")

print(f"[4] GPA: {studentInfo[3]}")

-----

Cập nhật: 31/10/2024

Bài sau: Python căn bản (15): Python Lists (cont.2)

-----

[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ệ