A.I, Data and Software Engineering

Advanced python part 2

A

In part 1, we introduced advanced string, bytes manipulation in Python. This article covers some advanced python knowledge with built-in functions and other useful tools for sequence iteration, data transformation.

Useful built-in functions

  • Use any() to return true if any of the sequence values are true
  • Use all() to return true only if all values are true
  • Quickly find the minimum/maximum value in a sequence by using min() and max()

Iterators

There are several methods to loop through elements in a sequence.

  • Use iter() to create an iterator over collection
  • Use enumerate() reduces code and provides a counter (index)

We now can run the example using the file created.

Use enumerator with zip to loop through combined sequences.

Itertools

We are demonstrating a couple of infinite iterators, and these are iterators that will generate values for as long as you need them and they just never end. First is called cycle, and it does what its name implies, it cycles over a set of values. 

The next infinite iterator we’re going to create is called a count iterator. It creates a counter which defaults to zero. I can also give it a step value, which defaults to one but I’ll make it 10.

It is also useful to use itertools to accumulates value.  Now it defaults to addition:

I can change the default addition function with the built-in max function. It will then replace all values from the index of the maximum value to the max value.

There are also many useful tools from itertools package to handle files. For example to read a file as chunks of lines. To achieve that, the islice() method from the itertools module comes into play. Also, it works as an iterator, and returns a chunk of data that consists of n lines. At the end of the file, the result might be shorter, and finally the call will return an empty list.

You may be interested in the advanced python method to find object size.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.