Python căn bản (16): Python Lists (cont.3)

16. Python Lists (cont.3)

16.1 List Comprehensions

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement with a conditional test inside.

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

newlist = []

 

for x in fruits:

  if "a" in x:

    newlist.append(x)

 

print(newlist)

With list comprehension you can do all that with only one line of code:

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

 

newlist = [x for x in fruits if "a" in x]

 

print(newlist)

The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition

The condition is like a filter that only accepts the items that evaluate to True.

Example

Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

The condition if x != "apple"  will return True for all elements other than "apple", making the new list contain all fruits except "apple".

The condition is optional and can be omitted.

Example

With no if statement:

newlist = [x for x in fruits]

Iterable

The iterable can be any iterable object, like a list, tuple, set etc.

Example

You can use the range() function to create an iterable:

newlist = [x for x in range(10)]

Same example, but with a condition.

Example

Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 5]

Expression

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list.

Example

Set the values in the new list to upper case:

newlist = [x.upper() for x in fruits]

You can set the outcome to whatever you like.

Example

Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]

The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome.

Example

Return "orange" instead of "banana":

newlist = [x if x != "banana" else "orange" for x in fruits]

The expression in the example above says:

"Return the item if it is not banana, if it is banana return orange".

16.2 Sort Lists

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default.

Example

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort()

print(thislist)

Example

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]

thislist.sort()

print(thislist)

Sort Descending

To sort descending, use the keyword argument reverse = True.

Example

Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort(reverse = True)

print(thislist)

Another example:

thislist = [100, 50, 65, 82, 23]

thislist.sort(reverse = True)

print(thislist)

Customize Sort Function

You can also customize your own function by using the keyword argument key = function.

The function will return a number that will be used to sort the list (the lowest number first).

Example

Sort the list based on how close the number is to 50:

def myfunc(n):

  return abs(n - 50)

 

thislist = [100, 50, 65, 82, 23]

thislist.sort(key = myfunc)

print(thislist)

Case Insensitive Sort

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters.

Example

Case sensitive sorting can give an unexpected result:

thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.sort()

print(thislist)

Luckily we can use built-in functions as key functions when sorting a list.

So if you want a case-insensitive sort function, use str.lower as a key function.

Example

Perform a case-insensitive sort of the list:

thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.sort(key = str.lower)

print(thislist)

Reverse Order

What if you want to reverse the order of a list, regardless of the alphabet?

The reverse() method reverses the current sorting order of the elements.

Example

Reverse the order of the list items:

thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.reverse()

print(thislist)

16.3 Copy and Join Lists

Copy a 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.

You can use the built-in List method copy() to copy a list.

Example

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

mylist = thislist.copy()

print(mylist)

Use the list() method

Another way to make a copy is to use the built-in method list().

Example

Make a copy of a list with the list() method:

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

mylist = list(thislist)

print(mylist)

Use the slice Operator

You can also make a copy of a list by using the : (slice) operator.

 

Example

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

mylist = thislist[:]

print(mylist)

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways is by using the + operator.

Example

Join two list:

list1 = ["a", "b", "c"]

list2 = [1, 2, 3]

 

list3 = list1 + list2

print(list3)

Another way to join two lists is by appending all the items from list2 into list1, one by one.

Example

Append list2 into list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

 

for x in list2:

  list1.append(x)

 

print(list1)

Or you can use the extend() method, where the purpose is to add elements from one list to another list.

Example

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

 

list1.extend(list2)

print(list1)

16.4 List Methods

Python has a set of built-in methods that you can use on lists.

Method            Description

append()          Adds an element at the end of the list

clear()              Removes all the elements from the list

copy()              Returns a copy of the list

count()             Returns the number of elements with the specified value

extend()           Add the elements of a list (or any iterable), to the end of the current list

index()             Returns the index of the first element with the specified value

insert()             Adds an element at the specified position

pop()                Removes the element at the specified position

remove()         Removes the item with the specified value

reverse()         Reverses the order of the list

sort()                Sorts the list

16.5 Exercise

1. Consider the following code:

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

newlist = [x for x in fruits if x == 'banana']

What will be the value of newlist?

A. ['apple', 'cherry']

B. ['banana']

C. True

D. False

2. What is the correct syntax for making a copy of a list?

A. list2 = list1

B. list2 = list1.copy()

C. list2.copy(list1)

D.  list2 = ref(list1)

3. What is the correct syntax for joining list1 and list2 into list3?

A. list3 = join(list1, list2)

B. list3 = list1 + list2

C. list3 = [list1, list2]

D. list3 = connect(list1, list2)

4. Write a program to input a string from the keyboard that contains a combination of the lower and upper case letters, then rearrange the characters of a string so that all lowercase letters should come first.

Input:

s1: hiBacTeo 

Expected output:

            hiaceoBT

5. Write a python program that allows the user to input a list of numbers from the keyboard. The user enters the character "q" to finish entering the list. Remove duplicate numbers from the list.

Input: 

[1, 2, 3, 40, 2, 1, 5]

Expected output:

[1, 2, 3, 40, 5]

-----

The answer hints:

1(B), 2(B), 3(B), 4()

4. Write a program to input a string from the keyboard that contains a combination of the lower and upper case letters, then rearrange the characters of a string so that all lowercase letters should come first.

Input:

s1: hiBacTeo 

Expected output:

            hiaceoBT

[code16_4.py]

# user input string from the keyboard

s1 = input("Enter a string:")

 

# create 2 strings to store lower and upper characters

lowerString = []

upperString = []

 

for char in s1:

    if char.islower():

        lowerString.append(char)

    elif char.isupper():

        upperString.append(char)

# concatenate lowerString and upperString        

resultString = lowerString + upperString

 

# convert a character list into string

resultString = ''.join(resultString)

 

print(resultString)

[code16_5.py]

#create a number list

numbers = []

 

# input a character list from the keyboard, enter "q" to quit

while True:

    number = input("Enter a number (or 'q' to quit):")

    if number == 'q':

        break

    else:

        numbers.append(number)

print(numbers)

 #create a unique number list

uniqueNumbers = []

 

 #remove the duplicate item from the numbers

for i in numbers:

    if i not in uniqueNumbers:

        uniqueNumbers.append(i)

        

print(uniqueNumbers)

-----

Cập nhật: 1/11/2024

Bài sau: Python căn bản (17): Python Tuples

-----

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