# 11 classic use cases of list and tuple

Keywords: Python Back-end

Hello, I'm brother Deng,

Today, I'd like to introduce 11 classic use cases of list and tuple. Let's have a look!

### 1. Judge whether there are duplicate elements in the list

We can implement an is to judge whether it is repeated or not_ The duplicated method uses the count method encapsulated in the list to judge the occurrence times of each element x in the list in turn.

If it is greater than 1, it returns True immediately, indicating that there is a duplicate.

If the function does not return after traversal, it indicates that there are no duplicate elements in the list and returns False.

```def is_duplicated(list):
for item in list:
#  Determine the number of times item appears in the list
if list.count(item) > 1:
return True
return False

if __name__ == '__main__':
lis = [45, 89, 23, 45, 36, 78, 15, 59, 35, 21, 75, 89, 36]
print(is_duplicated(lis))

'''
True
'''```

### Method 2: judge whether there are duplicate elements in the list

set()   Function to create an unordered set of non repeating elements. You can test the relationship, delete duplicate data, and calculate intersection, difference, union, etc.

The above method is not concise, and it is more convenient to judge with the help of set

```def is_duplicated(lst):
return len(lst) != len(set(lst))

if __name__ == '__main__':
lis = [45, 89, 23, 36, 78, 15, 59, 35, 21, 75]
print(is_duplicated(lis))

'''
False
'''```

### two   List inversion

One line of code realizes list inversion, which is very concise.

We can use python slicing [:: - 1]   Generate reverse index (negative sign indicates reverse), slice with step size of 1.

```def reverse(lst):
#  Reverse the list in one step according to the slice
return lst[::-1]

if __name__ == '__main__':
lis = [45, 89, 23, 36, 78, 15, 59, 35, 21, 75]
print('Forward list', lis)
print('Reverse list', reverse(lis))

'''
Forward list [45, 89, 23, 36, 78, 15, 59, 35, 21, 75]
Reverse list [75, 21, 35, 59, 15, 78, 36, 23, 89, 45]
'''```

### 3. Find all duplicate elements in the list

Traverse the list. If the number of occurrences is greater than 1 and is not in the return list RET, it will be added to ret.

```def find_duplicated(lis):
new_list = []
for item in lis:
if lis.count(item) > 1 and item not in new_list:
new_list.append(item)
return new_list

if __name__ == '__main__':
lis = [45, 89, 23, 36, 78, 15, 59, 35, 21, 75, 89, 15, 21]
print('Repeating elements:', find_duplicated(lis))

'''
Repeating elements: [89, 15, 21]
'''```

4. The generator generates Fibonacci sequence

Fibonacci sequence, also known as golden section sequence

The Fibonacci sequence is generated by Python generator to ensure the simplicity of the code,

It also saves memory:

```def fibonacci(n):
a, b = 1, 1
for x in range(n):
yield a
a, b = b, a + b

if __name__ == '__main__':
print(list(fibonacci(10)))

'''
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
'''```

5. More parameters

The parameter with a * is a variable location parameter, which means that any number of location parameters can be passed in.

Let's find the one with the most elements in many lists:

```def max_len(*lists):
# The key function defines how to compare sizes: the lambda parameter v is an element in lists.
return max(*lists, key=lambda v: len(v))

if __name__ == '__main__':
print('The longest list is:', max_len([1, 2, 3], [4, 5, 6, 7], [8, 9, 10]))

'''
The longest list is: [4, 5, 6, 7]
'''```

Return the first element of the list. Note that when the list is empty, return None.

```def head(lst):
return lst[0] if len(lst) > 0 else None

if __name__ == '__main__':

'''
'''```

7. Find the end of the table

In Python, we can use index - 1 to get the last element of the list.

```def tail(lst):
return lst[-1] if len(lst) > 0 else None

if __name__ == '__main__':
print('List tail element:', tail([-9, 8, 9, 10, 100]))

'''
List elements: 100
'''```

### 8. Print multiplication table

For for outer loop once, print(), line feed; The inner layer loops once and prints an equation.

```def mul_table():
for i in range(1, 10):
for j in range(1, i + 1):
print(f'{j}x{i}={i * j}\t', end='')
print()    #  Print a newline

if __name__ == '__main__':
mul_table()

'''
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
'''```

9. Splicing elements

zip()   The function is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return a list composed of these tuples.

Similar to the following:

```a = [1, 11, 111]
b = [2, 22, 222]
print(list(zip(a, b)))

'''
[(1, 2), (11, 22), (111, 222)]
'''```

t[:-1]: cut off the last element from the original list;

t[1:]: cut off the first element from the original list;

zip(iter1, iter2): realize the splicing of elements at the corresponding indexes of iter1 and iter2.

```def pair(t):
return list(zip(t[:-1], t[1:]))

if __name__ == '__main__':
print(pair([4, 5, 6, 7]))
print(pair(range(10)))

'''
[(4, 5), (5, 6), (6, 7)]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
'''```

### 10. Sample sampling

In the built-in random module, there is a sample function to realize the "sampling" function.

The following example is a random sample of 10 out of 100 samples.

First, a list lst with a length of 100 is created by using the list generation formula;

Then, sample samples 10 samples.

```from random import randint, sample

# randint generates random integers;
lst = [randint(0, 50) for x in range(100)]
print(lst)
print('The first five elements of the list:', lst[:5])
print('The last five elements of the list:', lst[-5:])

#  sample   from   lst   Medium sampling   ten   Elements
lst_sample = sample(lst, 10)
print('List ten random elements:', lst_sample)

'''
[46, 13, 8, 14, 2, 35, 16, 18, 29, 28, 0, 14, 4, 31, 26, 26, 17, 31, 26, 3, 17, 29, 14, 9, 42, 11, 27, 0, 1, 39, 34, 35, 34, 6, 50, 40, 30, 40, 44, 2, 0, 15, 12, 3, 34, 7, 40, 29, 14, 15, 27, 39, 6, 32, 1, 38, 35, 26, 50, 27, 11, 2, 28, 33, 49, 47, 43, 44, 47, 23, 33, 15, 19, 36, 31, 49, 42, 6, 13, 21, 1, 29, 12, 9, 46, 43, 37, 18, 22, 47, 36, 8, 12, 4, 39, 17, 48, 4, 33, 21]
The first five elements of the list: [46, 13, 8, 14, 2]
The last five elements of the list: [17, 48, 4, 33, 21]
List ten random elements: [30, 12, 40, 31, 47, 42, 6, 14, 14, 49]
'''```

### 11. Re wash data set

The shuffle function in the built-in random can flush the data.

It is worth noting that shuffle shuffles the input list in place to save storage space.

```from random import shuffle, randint
lst = [randint(0, 30) for _ in range(100)]
print(lst[:5])

#  Re washing data
shuffle(lst)
print(lst[:5])

'''
[30, 27, 8, 25, 14]
[2, 29, 29, 5, 14]
'''```