Lists in Python are one of the most common data structures we have, and one of the most powerful! Python lists are very rich and have many hidden tricks that go undiscovered.

Use Python to filter lists

1. Use Filter ()

The filter () function takes two arguments: the function and the iterable. In this case, we will define a function and filter a list.

Let’s try it out with an example! We’ll start with the list and filter out all items less than 3:

Original_list = [1,2,3,4,5] def filter_three(number):return number > 3

filtered = filter(filter_three, original_list)

filtered_list = list(filtered)

print(filtered_list)
# Returns (4, 5)
Copy the code

Let’s see what’s happening here:

  • We defined the original list
  • Then define a function that takes an argument (” number “). If the number is greater than 3, the function returns True.
  • We define an entry (” filtered “) that applies the filter function. Our item is filtered and is the filter object.
  • Finally, we create “filtered_list” and replace the list function with filtered objects.

2. Have a list understanding

Similarly, we can understand filtered lists in terms of lists. Remember that list comprehension is a quick and easy way to define and modify lists.

Let’s see how list comprehension can accomplish the previous task:

Original_list = [1,2,3,4,5] filtered_list = [numberfor number in original_list if number > 3]

print(filtered_list)

# Return (4, 5)
Copy the code

As you can see from these two examples, list comprehension is a simpler, faster way to filter lists.

Modify the list

1. Use Map () function

The Python Map function allows us to apply functions to each item in the iterable.

Suppose we have a list and we want to return the square of each number. We can do this using the map () function. Let’s see how it works:

Original_list = [1,2,3,4,5] def square(number):return number ** 2

squares = map(square, original_list)

squares_list = list(squares)

print(squares)

# Returns [1, 4, 9, 16, 25]
Copy the code

Let’s explore what’s going on here:

First, we define the original list and a function that returns its argument squared (” number “).

Then, we create a new variable named “squares”, which is the result of the map function with the function and the original list as parameters.

Finally, we create another new variable and apply the list function to the squares variable.

This method is a bit complicated! Now let’s look at the list to understand!

2. Have a list understanding

We can modify list items using list comprehension. This is even an easier and more elegant way to write our code.

Let’s try it!

Original_list = [1,2,3,4,5] squares_list = [number ** 2for number in original_list]

print(squares_list)

# Returns [1,4,9,16,25]
Copy the code

Merge the list with the Zip () function

In some cases, you may need to merge two or more lists. This is what the zip () function does: at each index, it creates an object containing the corresponding element of the list.

Let’s try it out with an example:

Numbers = [1,2,3]'a'.'b'.'c']

combined = zip(numbers, letters)

combined_list = list(combined)

# returns [(1, 'a'), (2, 'b'), (3, 'c')]
Copy the code

Reverse the list

Python lists are ordered data structures. Therefore, the order of items is important. Sometimes we may need to reverse the items in the list, which can be easily done using the Python slicing operation.

Let’s try it out with an example:

Reversed_list = original_list[::-1] original_list = original_list[::-1]print(reversed_list)

# Returns: [5,4,3,2,1]
Copy the code

Check membership in the list

Sometimes we want to see if there is an item in the list.

We can do this simply by using the IN operator.

games = ['Yankees'.'Yankees'.'Cubs'.'Blue Jays'.'Giants']

def isin(item, list_name):
  if item in list_name: print(f"{item} is in the list!")
  else: print(f"{item} is not in the list!")

isin('Blue Jays', games)
isin('Angels', games) 

# Returns
#Blue Jays on the list!
#Angels not on the list!
Copy the code

Find the most common items in the list

If you want to find the most common items in the list. For example, you might have a list of heads and tails winners and want to know which won the most.

games = ['heads'.'heads'.'tails'.'heads'.'tails']
items = set(games)
print(max(items, key = games.count))
Copy the code

Let’s see what this code does:

  • We define a list with the results of five heads or tails games;
  • We defined a collection of all the items in the list. The set () function filters out duplicates in the list;
  • Finally, we apply Max () to the itemset and use the key parameter as the highest count of elements in the set.

Expand the list

Sometimes we get a list that contains other lists, that is, tables within tables. You can easily do this using list comprehension!

Let’s try it:

Nested_list = [[1, 2, 3], [4 and 6], [7,8,9]] flat_list = [Ifor j in nested_list for i in j]

print(flat_list)

# Returns [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

Eight, check uniqueness

If you need to check that all items in a list are unique, you can use the collection feature to do so!

A collection in Python is similar to a list (because it is mutable and unordered), but it can contain only unique items.

To do this, we need to use a function to convert the list to a collection and compare the lengths of the two items:

Def list = [1,1,2,3,4] def list = [1,1,2,3,4] def list = [1,1,2,3,4]if len(list) == len(set(list)):
    print('Unique! ')
  else: print('Not Unique! ')

isunique(list1)
isunique(list2)

# Returns 
# uniqueness
# is not the only
Copy the code

Wenyuan network, only for the use of learning, if there is infringement please contact delete.

You will definitely encounter difficulties in learning Python. Don’t panic, I have a set of learning materials, including 40+ e-books, 800+ teaching videos, covering Python basics, crawlers, frameworks, data analysis, machine learning, etc. Shimo. Im/docs/JWCghr… Python Learning Materials

Follow the Python circle and get good articles delivered daily.