# list

## 1. Create

```In [54]: a = list()

In [55]: a
Out[55]: []```

Or:

```In [56]: a = []

In [57]: a
Out[57]: []```

It can also be assigned during direct initialization:

```In [58]: a = [1,2,3,'w',(2,3)]

In [59]: a
Out[59]: [1, 2, 3, 'w', (2, 3)]```

• append() adds an element to the end of the list
```In [60]: a.append(5)

In [61]: a
Out[61]: [1, 2, 3, 'w', (2, 3), 5]
```
• insert() inserts an element at the specified location in the list
```In [62]: a.insert(3,4)

In [63]: a
Out[63]: [1, 2, 3, 4, 'w', (2, 3), 5]```
• extend() to add multiple elements

```In [83]: a = [1, 2, 3, 4, 'w', (2, 3), 5]

In [84]: a.extend([1,2,3])

In [85]: a
Out[85]: [1, 2, 3, 4, 'w', (2, 3), 5, 1, 2, 3]```

## 3. Delete element

• Delete using del (specify location)
```In [63]: a
Out[63]: [1, 2, 3, 4, 'w', (2, 3), 5]

In [64]: del a[1]

In [65]: a
Out[65]: [1, 3, 4, 'w', (2, 3), 5]
```
• Use pop() to delete
```In [65]: a
Out[65]: [1, 3, 4, 'w', (2, 3), 5]

In [66]: val = a.pop()

In [67]: val
Out[67]: 5

In [68]: a
Out[68]: [1, 3, 4, 'w', (2, 3)]```

The last value pops up by default, or the value of the specified index

`val = a.pop(1)`
• remove() removes elements based on values
```In [68]: a
Out[68]: [1, 3, 4, 'w', (2, 3)]

In [69]: a.remove('w')

In [70]: a
Out[70]: [1, 3, 4, (2, 3)]```

# set

## 1. Create

`a = set()`

perhaps

`a = {1,2,3,4,'wang',(2,3)}`

In this way, the initial value must be assigned, otherwise the dictionary is created

```In [78]: a
Out[78]: {(2, 3), 1, 2, 3, 4, 'wang'}

In [80]: a
Out[80]: {(2, 3), 1, 2, 3, 4, 5, 'wang'}```

If the added value is already in the collection, do not operate. (no duplicate elements in collection)

```In [86]: a = {(2, 3), 1, 2, 3, 4, 5, 'wang'}

In [87]: a.update([5,6,7])

In [88]: a
Out[88]: {(2, 3), 1, 2, 3, 4, 5, 6, 7, 'wang'}```

Note: set has no order

## 3. Delete element

• remove() deletes the specified element in the collection, and reports an error if the element does not exist
• pop() randomly deletes an element in the collection and returns the deleted element (no parameter, distinguished from the list)
• discard() deletes the specified element in the collection, and does nothing if the element does not exist

Elements cannot be removed by index because the collection is out of order

## 4. Emptying and combining

```In [92]: a
Out[92]: {(2, 3), 1, 2, 3, 4, 5, 6, 7, 'wang'}

In [93]: a.clear()

In [94]: a
Out[94]: set()```

Note: for more collection operations, please refer to: The operation and application of collection in python

Tags: Python

Posted on Thu, 04 Jun 2020 11:16:33 -0400 by Riseykins