Note that Python list comprehensions are always confusing

Introduction

I'm using Python at work "Ah, the process of making a list here, if you use list comprehension notation, you can write it concisely." I may think. However, there are surprisingly few situations where I want to write list comprehensions, so when I decided to write it, "Oh, how do you write a list comprehension? Well, I don't have time and I want to loop as usual." It's a shame, so including the meaning of the memorandum for myself.

What is list comprehension?

When you first heard this word, what was in your head? Full of marks. .. .. To put it very simply, list comprehension is ** How to create list data in one line ** is.

However, not everything can be written in one line, and the process of creating a list in a loop can be written in one line (although there is some misunderstanding). I myself thought, "The code I write at work is complicated!", But it can be used unexpectedly.

How to write

Normal loop (this is not a list comprehension)

data = []
for i in range(10):
    data.append(i)

print(data)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehension

print([i for i in range(10)])
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Commentary

The result of a list comprehension is the same as a normal loop. However, the list comprehension notation requires less description. And the code is concise and easy to read. (It's hard to read unless you get used to it.)

Let's take a look at the list comprehension code.

[...] As you know, this creates a list, eliminating the need for data = [] in regular loops.

for i in range(10) This is the same for regular loops and list comprehensions. However, : is not required for list comprehensions.

i for i in range(10) The first ʻi that appears contains the value of ʻi (the second ʻi) that was retrieved in the loop. The value of ʻi that appears first is rewritten for each loop. The ʻi` is added to the list for the number of loops.

A little more concrete

I think it's easier to understand if it's a little more specific, so I'll explain it in the next case.

case 1

If you want to process the data in the list. For example, if you want to add @ to each data in the list ['aa','b','ccc'].

items = ['aa', 'b', 'ccc']
print([item + '@' for item in items])
# ['aa@', 'b@', 'ccc@']

I'm creating another list by adding @ to the data in ʻitems`. From the list data, another ** list data was created in one line **.

Case 2

When you want to add another character in the middle of a character string according to a fixed rule such as data processing. For example, if you want to add - to the data ʻabcdefgh` for each character.

items = 'abcdefgh'
print('-'.join([item for item in items]))
# a-b-c-d-e-f-g-h

Here, ** list data is created in one line from a character string. ** ** The data in that list is joined with - to return it to a string.

[Addition] I have received a comment, so I will add it. This was possible without using list comprehensions. You don't have to waste it.

items = 'abcdefgh'
print('-'.join(items))
# a-b-c-d-e-f-g-h

By the way, if you want to add - to every two characters.

items = 'abcdefgh'
print('-'.join([items[i*2: i*2+2] for i in range(int(len(items)/2))]))
# ab-cd-ef-gh

It feels a little overloaded, so is it like this?

items = 'abcdefgh'
loop_count = int(len(items)/2)
print('-'.join([items[i*2: i*2+2] for i in range(loop_count)]))
# ab-cd-ef-gh

[Addition] I also received a comment, so I will add it. In the above case, a counter called ʻi` is used, so out-of-range access may occur. It is a writing style that avoids it.

items = 'abcdefgh'
print('-'.join(ch1+ch2 for ch1, ch2 in zip(items[::2], items[1::2])))
# ab-cd-ef-gh

I found that the last character is not output when the number of characters is odd, even if the counter is used or not. I would use a counter, but I was able to avoid it.

import math
items = 'abcdefghi'
loop_count = math.ceil(len(items) / 2)
print('-'.join([items[i*2: i*2+2] for i in range(loop_count)]))
# ab-cd-ef-gh-i

Finally

In case 1, the data in the list is processed to create another list. Case 2 is a sample of processing a character string to make a list.

Both cases can be achieved using loops, List comprehensions make your code simple and concise.

Recommended Posts

Note that Python list comprehensions are always confusing
Python list comprehensions that are easy to forget
Note
Note
Note
Django note 4
pyenv note
GroupBy Note
Non-local means
argparse note
Django Note 5
Note: Python
Ansible Note
Python note
Django Note 1
direnv note
Django note 3
Django note 2
[Note] RepresenterError
Note that Python list comprehensions are always confusing
Python list comprehensions and generators
Note that it supports Python 3
python Note: Determine if command line arguments are in the list
Note: Python
10 Python errors that are common to beginners
Python note
[Python] list
[Note] Terms that are difficult to remember
[Python] Solution to the problem that elements are linked when copying a list
List comprehensions are no longer slow in PyPy 7.3.1
List of links that machine learning beginners are learning
Note: Python Decorator
Python basics: list
Python programming note
[Python] Learning Note 1
Python study note_004
Python study note_003
Python> Comprehension / Comprehension> List comprehension
[Note] openCV + python
Note: List comprehension
Python beginner's note
Python list manipulation
Mayungo's Python Learning Note: List of stories and links
Implemented List and Bool in Python and SQLite3 (personal note)
Note that writing like this with ruby is writing like this with python
Makes you think that Python regular expressions are great
Things to note when initializing a list in Python
Python3 comprehension (List, dictionary) that I have seen somewhere