Python Intermediate and Advanced

Python Intermediate_001: List Compression (English Version)

codeaddict 2024. 12. 22. 15:14

"이 블로그 포스트는 영어로 작성되었지만, 영어에 익숙하지 않은 분들을 위해 다음 글에서 한국어 버전도 제공하고 있습니다."

Python Advanced _ List Compression

 

Understanding Python List Comprehensions

Python list comprehensions are a concise and efficient way to create a new list from an existing iterable. This allows you to write code that is not only shorter, but also more readable and Pythonic. In this tutorial, we will first forshow you the traditional loop approach, convert it to a list comprehension, and then explain how to use list comprehensions.


What is a list comprehension?

List comprehensions are a concise syntax for creating lists by performing operations on each element of an existing iterable object, optionally including conditions to filter the elements.

syntax:

[ Expression for items in repeatable if condition ]
  • Expression  : Output for each element.
  • item  : The current element being repeated.
  • Repeatable  : A repeating sequence (e.g. a list, range, or string).
  • Condition (optional): A filter that determines whether to include the element in the output list.

Example of list comprehension

Example 1: Square of a number

Using a for loop:

numbers = [ 1 , 2 , 3 , 4 , 5 ] 
Squares = [] 

for x in numbers: 
    squares.append(x** 2 ) 

print (squares) 
# Output: [1, 4, 9, 16, 25]

Using list comprehension:

number = [ 1 , 2 , 3 , 4 , 5 ] 
Square = [x** 2   for x in numbers] 

print (square) 
# Output: [1, 4, 9, 16, 25]

Example 2: Filtering even numbers

Using a for loop:

even_numbers = []

for x in range(1, 11):
    if x % 2 == 0:
        even_numbers.append(x)

print(even_numbers)
# Output: [2, 4, 6, 8, 10]

Using list comprehension:

even_numbers = [x for x in range(1, 11) if x % 2 == 0]

print(even_numbers)
# Output: [2, 4, 6, 8, 10]

Example 3: Convert a string to uppercase

Using a for loop:

words = ['apple', 'banana', 'cherry']
uppercase_words = []

for word in words:
    uppercase_words.append(word.upper())

print(uppercase_words)
# Output: ['APPLE', 'BANANA', 'CHERRY']

Using list comprehension:

words = ['apple', 'banana', 'cherry']
uppercase_words = [word.upper() for word in words]

print(uppercase_words)
# Output: ['APPLE', 'BANANA', 'CHERRY']

Example 4: Nested loops in a list comprehension

Using nested forloops:

matrix = []

for i in range(1, 4):
    for j in range(1, 4):
        matrix.append((i, j))

print(matrix)
# Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Using list comprehension:

matrix = [(i, j) for i in range(1, 4) for j in range(1, 4)]

print(matrix)
# Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Example 5: Conditional Expressions in List Comprehensions

Using a for loop:

numbers = [1, 2, 3, 4, 5]
labels = []

for x in numbers:
    if x % 2 == 0:
        labels.append("even")
    else:
        labels.append("odd")

print(labels)
# Output: ['odd', 'even', 'odd', 'even', 'odd']

Using list comprehension:

numbers = [ 1 , 2 , 3 , 4 , 5 ] 
labels = [ "even"   if x % 2 == 0   else   "odd"   for x in numbers] 

print (labels) 
# Output: ['odd', 'even', 'odd', 'even', 'odd']

When to use list comprehension

Use list comprehension when:

  1. Create a list from repeatable items.
  2. I want to make my code more concise and readable.
  3. The logic in understanding is not overly complex.

Do not use list comprehension in the following cases:

  1. The task consists of multiple steps or is difficult to understand.
  2. Excessive nesting or complex logic reduces readability.