# python learning notes -- Liao Xuefeng (17, list generation)

The generated form used to create the list.

To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can use list(range(1, 11)): note 11

```>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]```

How to generate [1x1, 2x2, 3X3,..., 10x10]? The first method is circulation:

```>>> L = []
>>> for x in range(1, 11):
...    L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```

However, the cycle is too cumbersome, and the list generation can use one line of statements instead of the cycle to generate the above list:

```>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
```

When writing list generation, put the element x * x to be generated first, followed by the for loop

You can also use two layers of loops to generate a full spread:

```>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']```

List all the files and directory names in the current directory, which can be realized by one line of code:

```>>> import os # Import the os module. The concept of the module will be discussed later
>>> [d for d in os.listdir('.')] # os.listdir can list files and directories
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']```

items() of dict can iterate key and value at the same time:

```>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
...     print(k, '=', v)
...
y = B
x = A
z = C
```

Therefore, list generation can also use two variables to generate a list:

```>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']```

Finally, change all strings in a list to lowercase:

```>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']```

### Practice

If the list contains both strings and integers, since there is no lower() method for non string types, the list generation will report an error:

```>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
```

Use the built-in isinstance function to determine whether a variable is a string:

```>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False```

Please modify the list generation. Add if statement to ensure that the list generation can execute correctly:

```L1 = ['Hello', 'World', 18, 'Apple', None]
s=[L2.lower() for L2 in L1 if isinstance(L2,str)==1]
print(s)```

Posted on Mon, 02 Dec 2019 00:08:12 -0500 by digitalgod