---
# System prepended metadata

title: Python リスト内包表記 2021-07-24
tags: [Python, リスト内包表記]

---

---
lang: ja-jp
breaks: true
---
# Python リスト内包表記 2021-07-24

```python=
squares = [i**2 for i in range(5)]
print(squares)
# [0, 1, 4, 9, 16]
```

```python=
odds = [i for i in range(10) if i % 2 == 1]
print(odds)
# [1, 3, 5, 7, 9]
```

```python=
odd_even = ['odd' if i % 2 == 1 else 'even' for i in range(10)]
print(odd_even)
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
```

```python=
l_str1 = ['a', 'b', 'c']
l_str2 = ['x', 'y', 'z']

l_zip = [(s1, s2) for s1, s2 in zip(l_str1, l_str2)]
print(l_zip)
# [('a', 'x'), ('b', 'y'), ('c', 'z')]
```

```python=
l_enu = [(i, s) for i, s in enumerate(l_str1)]
print(l_enu)
# [(0, 'a'), (1, 'b'), (2, 'c')]
```

```python=
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flat = [x for row in matrix for x in row]
print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

###### tags: `Python` `リスト内包表記`
