Please Master These 10 Python Functions…

Tech With Tim
7 Jun 202422:16

Summary

TLDRThis script offers an in-depth exploration of ten essential Python functions that every programmer should master. Starting with the versatile 'print' function, it covers its advanced parameters like 'Sep' and 'end'. The script then introduces the 'help' function for quick access to documentation, followed by 'range', 'map', 'filter', 'sum', 'sorted', 'enumerate', 'zip', and the file handling 'open' function. Each function is explained with examples and use cases, emphasizing their efficiency and utility in coding, concluding with best practices for file operations using context managers.

Takeaways

  • 📝 The `print` function in Python is versatile, allowing for customization of separators and end characters to control the output format.
  • 🔍 The `help` function serves as an in-built documentation tool, providing quick access to a function's docstrings without needing to search online.
  • 🔢 The `range` function is essential for generating sequences of numbers with customizable start, stop, and step values, and can be converted to a list for direct usage.
  • 🗺️ The `map` function applies a given function to every item in an iterable, streamlining the process of performing operations across collections.
  • 📝 The `filter` function selectively filters items in an iterable based on a provided function that returns a boolean value, deciding whether to include each item.
  • 🌐 The `sum` function quickly calculates the total of numbers in an iterable, with the option to set a custom starting value for the summation.
  • 🔄 The `sorted` function sorts iterables in ascending or descending order, with the ability to define custom sort keys through a function.
  • 🔑 The `enumerate` function pairs each item in an iterable with its index, simplifying loops that require both index and value access.
  • 🔗 The `zip` function combines multiple iterables into a single iterable of tuples, efficiently merging corresponding elements from each iterable.
  • 📖 The `open` function is crucial for file operations, offering different modes for reading, writing, and appending, with the emphasis on using context managers for proper resource management.

Q & A

  • What is the primary purpose of the 'print' function in Python?

    -The 'print' function in Python is used to display output to the console or terminal. It can handle a mix of strings and variables, and allows for customization of the separator and end parameters to control the format of the output.

  • How can the 'print' function's default behavior of separating arguments with a space be changed?

    -The default behavior of the 'print' function can be changed by passing a different value to the 'sep' argument. For example, setting 'sep' to a pipe character '|' will replace the space with a pipe between arguments.

  • What does the 'end' argument in the 'print' function do?

    -The 'end' argument in the 'print' function determines what is printed at the end of the line. By default, it adds a newline character (' '), but it can be changed to any string, allowing for printing on the same line consecutively.

  • What is the 'help' function in Python and how is it used?

    -The 'help' function in Python is used to display the documentation of a given function or module. It reads the docstrings to provide information on usage and parameters, which is useful for quickly accessing documentation without needing to search online.

  • Can the 'help' function be used with user-defined functions?

    -Yes, the 'help' function can be used with user-defined functions as well. It prints the docstring associated with the function, which should be provided when the function is defined to describe its purpose and usage.

  • What is the 'range' function in Python and how does it work?

    -The 'range' function in Python generates a sequence of numbers. It can take one, two, or three arguments for start, stop, and step values, respectively. By default, it starts at 0 and steps by 1, going up to but not including the stop value.

  • How can the 'map' function be used to apply a function to every item in an iterable?

    -The 'map' function takes a function and an iterable as arguments, then applies the function to each item in the iterable. The results are returned as a map object, which can be converted to a list to view all the results at once.

  • What is the purpose of the 'filter' function in Python?

    -The 'filter' function is used to filter items in an iterable based on a given function. If the function returns True for an item, it is included in the result; otherwise, it is excluded.

  • What does the 'sum' function do and can it accept a starting value?

    -The 'sum' function calculates the total sum of all numeric items in an iterable. It can accept an optional 'start' parameter, which allows the summation to begin from a value other than zero.

  • How does the 'sorted' function work and what arguments can be used to modify its behavior?

    -The 'sorted' function sorts an iterable in ascending order by default. It can be modified by passing the 'reverse' argument set to True for descending order, or by using the 'key' argument with a function to determine the sorting criteria.

  • What is the 'enumerate' function used for and how does it simplify loops?

    -The 'enumerate' function is used to iterate over an iterable while having access to both the index and the value of each item. It simplifies loops by returning a tuple containing the index and value for each iteration, eliminating the need for manual index tracking.

  • Can the 'zip' function be used to combine multiple lists and how does it handle lists of different lengths?

    -Yes, the 'zip' function combines multiple iterables into a single iterable of tuples. It stops at the shortest iterable, thus handling lists of different lengths by not causing an index out of bounds exception.

  • What is the 'open' function used for and what are the common modes for file operations?

    -The 'open' function is used to open a file for various operations like reading, writing, and appending. The common modes are 'r' for reading, 'w' for writing (which truncates the file), and 'a' for appending to the end of the file.

  • Why is it recommended to use a context manager with the 'open' function?

    -Using a context manager with the 'open' function ensures that the file is properly closed after its operations are completed, even if an error occurs during the file manipulation process. It prevents memory leaks and ensures the file is not left open unintentionally.

Outlines

00:00

📘 Mastering Essential Python Functions

This paragraph introduces ten fundamental Python functions that are crucial for Python programmers to master due to their time-saving capabilities. The print function is highlighted as the first function, which is often the initial exposure for beginners. The paragraph explains the basic use of print, such as outputting strings and variables, and then delves into advanced features like the Sep and end arguments that modify the print behavior. It also touches on the help function, which is used to access the documentation of any Python function without needing to search online, and the range function, which is essential for generating sequences of numbers in loops or as lists. The importance of understanding these functions is emphasized for efficient Python programming.

05:00

🔢 Exploring Python's Range and Map Functions

The second paragraph continues the discussion on Python functions, focusing on the range function's ability to generate sequences of numbers with different start, stop, and step values. It demonstrates how to create ascending and descending sequences and how to convert a range object to a list for direct usage. The map function is introduced as a tool for applying a function to every item in an iterable, such as strings, lists, or tuples. Examples are given to show how map can simplify the process of applying functions like length to a list of strings or using lambda functions for custom operations on iterables.

10:01

📝 Understanding Python's Filter, Sum, and Sorted Functions

This paragraph delves into the filter function, which retains items in an iterable based on a condition set by a function. The sum function is then explained as a tool for calculating the total of numbers in an iterable, with the option to set a starting value for the sum. The sorted function is introduced for arranging items in an iterable in ascending or descending order, with additional arguments like reverse and key for custom sorting criteria. Practical examples are provided to illustrate the use of these functions in processing and manipulating data.

15:02

🔄 The Power of Enumerate and Zip Functions in Python

The fourth paragraph discusses the enumerate function, which simplifies the process of looping through an iterable with access to both the index and the value. It contrasts the traditional method of using range and index with the more concise enumerate approach. The zip function is then introduced as a powerful tool for combining multiple iterables into a single iterable of tuples, which is particularly useful when dealing with corresponding values in different lists. The paragraph demonstrates how zip can handle iterables of varying lengths and emphasizes its utility in cleaning up code and improving readability.

20:05

📖 Working with Files using Python's Open Function

The final paragraph of the script discusses the open function for file operations in Python. It explains how to open a file in different modes, such as read ('r'), write ('w'), and append ('a'), with a focus on the write mode that overrides existing files. The paragraph demonstrates writing to a file, the importance of closing the file to prevent memory leaks, and the best practice of using a context manager (the 'with' statement) to ensure files are properly closed after operations. It also touches on reading from files and appending content without overwriting existing data.

Mindmap

Keywords

💡print function

The 'print function' is a fundamental aspect of Python programming, used to display output to the console. It is introduced as the first function in the script, showcasing its simplicity yet powerful customization through arguments like 'sep' and 'end', which can alter the default behavior of separating printed items with a space and appending a newline character, respectively. For example, the script demonstrates changing the separator to a pipe symbol and the terminator to a space, which helps in formatting the output in a specific way.

💡help function

The 'help function' in Python serves as an interactive tool to access documentation for built-in functions, libraries, or user-defined functions without needing to search the internet. It reads and displays the docstrings, which are strings that describe what the function does, its parameters, and return values. The script illustrates using the help function with the 'print' function itself, as well as with a custom function called 'test_func', to show how it can be used to quickly access and understand the functionality of any function.

💡range function

The 'range function' is a versatile tool in Python for generating a sequence of numbers. It can be used with one, two, or three arguments to specify the start, stop, and step values, respectively. In the script, the range function is explained through various examples, such as generating a sequence from 0 to 9, starting from 2 up to but not including 10, and even creating a negative sequence by using a negative step value. It is also noted that 'range' returns an iterator, which must be converted to a list if a complete list of values is desired.

💡map function

The 'map function' applies a given function to each item of an iterable (like a list, tuple, or string) and returns a map object, which is an iterator. In the script, the map function is demonstrated by applying the 'len' function to a list of strings to get their lengths, and also by using a lambda function to append an 's' to each string in a list. This function is highlighted for its utility in performing operations on iterables in a concise and efficient manner.

💡filter function

The 'filter function' allows for the conditional extraction of elements from an iterable. It takes a function and an iterable, and returns an iterator consisting of those elements for which the function returns True. In the script, a custom function 'longer_than_four' is used to filter strings longer than four characters. The filter function is also shown being used with a lambda function to achieve the same result, demonstrating its use for both simple and complex filtering criteria.

💡sum function

The 'sum function' is used to return the total sum of all numeric values in an iterable. The script mentions that it can take an optional 'start' parameter, which allows the summation to begin from a value other than zero. For instance, adding '10' as the start value results in the initial sum being '10', and then adding the values from the iterable to it. This function is essential for quickly aggregating numerical data.

💡sorted function

The 'sorted function' takes an iterable and returns a new sorted list from the elements of the iterable. It can be customized to sort in ascending or descending order using the 'reverse' parameter, and to sort based on a specific function of the elements with the 'key' parameter. In the script, sorting a list of dictionaries by age using a lambda function as the key is demonstrated, showing how to control the sorting behavior for complex data structures.

💡enumerate function

The 'enumerate function' is used to add a counter to an iterable and return it in a form of an index sequence. It is commonly used in for loops when you need access to both the element and its index. The script explains that using 'enumerate' simplifies the process of looping over a list with access to indexes, as it returns a tuple containing the index and the value, eliminating the need for manual index handling.

💡zip function

The 'zip function' takes multiple iterables and aggregates them into a single iterable of tuples, where each tuple contains the i-th element from each of the input iterables. In the script, 'zip' is used to combine two lists, 'names' and 'ages', into a list of tuples, simplifying the process of iterating over paired data. It is also shown that 'zip' can handle multiple iterables and will stop at the shortest iterable's length, which is useful for aligning data from different sources.

💡open function

The 'open function' is used to open a file and is fundamental when working with file input/output operations in Python. It requires a file name and a mode, such as 'r' for reading, 'w' for writing (which truncates the file), and 'a' for appending. The script emphasizes the importance of closing files after operations to avoid memory leaks and recommends using the 'with' statement as a context manager for automatically handling file closing. It also demonstrates writing to and reading from files using 'open'.

Highlights

The print function in Python can be customized with additional arguments such as 'sep' to change delimiters.

The 'end' argument in the print function can be modified to avoid adding a newline character after printing.

The help function provides quick access to the documentation of any Python function, including custom ones.

The range function can generate sequences of numbers with customizable start, stop, and step values.

The map function applies a given function to every item in an iterable, simplifying operations on lists.

Lambda functions can be used with map for quick, one-liner function applications.

The filter function allows for conditional filtering of items in an iterable based on a provided function.

The sum function can calculate the total of numbers in an iterable and can take a starting value for the sum.

The sorted function can sort any iterable, with options to reverse the order and use a key function for custom sorting.

The enumerate function simplifies loops that require access to both the index and the value of iterable items.

The zip function pairs elements from multiple iterables into tuples, streamlining the process of merging related data.

The open function is essential for file operations in Python, with different modes for reading, writing, and appending.

Using the 'with' statement for file operations ensures proper closure and error handling.

The video provides practical examples of how to use Python's built-in functions to enhance coding efficiency.

Understanding and mastering these functions can significantly save time and improve the quality of Python code.

The video emphasizes the importance of exploring additional parameters of seemingly simple functions to unlock their full potential.

Transcripts

play00:00

If you write any code in Python, then you'll see these ten Python functions

play00:04

a ton and it's important you master them.

play00:06

Some of them may seem simple, but they have a lot of additional parameters

play00:09

that you need to understand as they can save you a ton of time.

play00:13

So with that said, let's dive in and look at function number one.

play00:16

So the first function we'll look at here is the print function.

play00:19

Now this is probably the first thing you learn when you learn Python.

play00:21

And it seems super basic.

play00:23

We can print out a few different things.

play00:25

We can separate them by commas.

play00:27

And you can see that we can print a mix of strings and variables.

play00:30

And when we do that, they'll get printed out separated by a space.

play00:34

But what you probably didn't know is that we can pass additional arguments

play00:37

to the print function that modify how it works.

play00:40

For example, I can pass the Sep argument here.

play00:43

So Sep is equal to and I'll go with something like a pipe.

play00:46

And now what will happen is rather than using a space

play00:49

as the delimiter or what goes in between, the different arguments

play00:52

we pass to the print function will use this pipe.

play00:56

So when I run the code now you see we get.

play00:58

My name is and then pipe Tim pipe and I am pipe 23 pipe years old.

play01:03

So we can override that default behavior, which is to use a space to separate

play01:07

all the different things we're printing.

play01:09

And in this case, we use a pipe.

play01:11

Now maybe instead we want to use a comma.

play01:13

So let's go back here and change that to a comma and print this out.

play01:16

And now you can see that we're printing things with a comma.

play01:18

This is quite useful especially when you want

play01:20

to print out things that have a certain formatting.

play01:22

And you don't want to do the manual formatting yourself.

play01:25

Now another thing we should know about the print

play01:26

function is how we change what gets printed at the end of the line.

play01:30

So you may not know this,

play01:31

but by default when you print something with this function, it's

play01:34

going to actually add a backslash n which is a new line

play01:38

character which will force the terminal to go to the next line.

play01:41

So when you print something else, it won't be on the same line.

play01:44

Now typically this is what you want.

play01:46

And that means when I run the code here you'll see

play01:48

we get these two print statements on separate lines.

play01:50

But sometimes you actually want to print things on the same line.

play01:54

So how do you do that.

play01:55

Well what we can actually do is we can override this end argument here,

play01:59

and we can pass this something different than the new line character.

play02:02

So I could pass a and is equal to a pipe and maybe put some spaces around it.

play02:06

And if we clear here and run you'll see.

play02:10

Now we get hello world.

play02:11

And at the end of this print statement it prints the pipe with the spaces.

play02:15

And then when we go to print the next line, it will happen on the same line here

play02:20

because we didn't move down to the next line.

play02:22

So now we're going to dive into the second function here which is the help function.

play02:26

But first I need to share with you something that's going to be very helpful.

play02:29

And that is the sponsor of this video.

play02:32

Today's video is sponsored by Male Trap,

play02:35

an email delivery platform that developers love.

play02:39

Now, what's cool about Male Trap?

play02:41

It's actionable analytics, the best in the industry

play02:44

with full statistics and drill down reports on each and every email you send.

play02:50

Male trap

play02:51

offers separate streams for transactional and bulk emails,

play02:54

SMTp and API integrations,

play02:57

plus SDK for major programing languages.

play03:01

At Male Trap, human support is available round the clock for all customers.

play03:06

Try today at Male trap.io.

play03:10

So hopefully you appreciated that segue there.

play03:12

But now let's have a look at the help function.

play03:15

Now the help function allows us to print out the documentation of a Python function.

play03:20

So we don't need to go to the internet to look it up.

play03:22

And we can really quickly get access to how a function works.

play03:25

Now what this will do is read the docstrings of a function

play03:28

and simply give it to us.

play03:29

So what I can do is something like help

play03:31

and then I can pass to this maybe the print function.

play03:34

And notice I'm not calling the print function, I'm just writing the name of it.

play03:38

And now when I run the code,

play03:39

you'll see that I actually print out all of the documentation for the print function.

play03:43

This is what's contained in the docstring for it.

play03:46

So you can see it says print kind of shows you an example of how it works.

play03:49

And then it gives you a description

play03:50

of the different arguments or the parameters for this function.

play03:53

Now this also works for your own functions.

play03:55

So let me show you that.

play03:57

So you can see here I've written a custom function called test func

play04:00

and I've just written a docstring for it just as an example.

play04:02

So we can see how this works.

play04:04

Now when I run my code here, notice it will actually give me

play04:07

the documentation of this function.

play04:09

So it says a b and then the return type.

play04:11

Again it's really just printing it with the docstring is that's written here.

play04:15

So this is useful for built in functions.

play04:16

But also when you're working with a library or code written by other people.

play04:20

So you don't need to search through and find the actual function definition.

play04:23

You can just use this help function.

play04:25

It will print it out for you.

play04:27

So the next function on my list is a very common one.

play04:29

And you've probably seen this, especially if you're working with a for loop.

play04:32

And that is range.

play04:33

Now as much as range can be used to iterate through values in a for loop.

play04:37

We can also use it just to generate a list of numbers.

play04:39

And I'll quickly walk through how it works because it is a very important function.

play04:43

So what range will do is generate a range of numbers starting at some value,

play04:48

stopping at some value, and stepping by some value.

play04:51

Now, by default, when you only pass

play04:53

one value here to the range function, this acts as the stop.

play04:57

That means it's going to go up to but not include this number.

play05:00

And it's going to start at one and step by one, which means go up by one each time.

play05:05

So if I run the code here,

play05:06

you can see that this gives us the values zero through nine again

play05:09

because we go to the stopping point, but we do not include it.

play05:12

Now if I have a second value here, something like two and then ten,

play05:16

this will act as the start value and this will act as the stop value.

play05:21

And now when I run this, you see that we will simply start at two.

play05:23

And we will go up to ten but not include it.

play05:25

If I decide to add a third value here, something like two,

play05:29

this will act as the step value

play05:31

and this will be the increment that we will go up by each time.

play05:34

So if I run this here we get 246, eight.

play05:37

Now this is quite useful.

play05:38

And we can do this

play05:39

in many different kind of ways to generate a lot of different sequences of numbers.

play05:43

For example,

play05:43

I can change this to a negative two and I can swap these values around and go

play05:47

maybe ten.

play05:48

And maybe we're actually going to go to something like negative ten.

play05:51

And now this will give us a negative range where we start at ten.

play05:54

And we subtract two each time until we hit the stopping value of negative ten,

play05:57

which we do not include.

play05:59

Very useful for for loops.

play06:00

But also if you convert this range into a list,

play06:03

then you can simply use it as a list of values.

play06:05

One thing to note if you print out range itself, which we can do here,

play06:10

you'll see that we actually get a range object.

play06:13

That's because range returns to a something known as an iterator.

play06:16

An iterator is something that we step through using kind of a specific process

play06:20

that I don't need to get into in this video.

play06:22

The point is,

play06:23

if you want to actually

play06:24

get an entire list of values, you do need to manually convert this to a list.

play06:29

Okay, so to do that, we just write the list function around range.

play06:32

And then as you saw before, it gives us a list of values

play06:35

rather than this range object which again is an iterator.

play06:38

Now the next function we're looking at is the map function.

play06:41

Now a map function

play06:42

allows us to apply a function to every single item in an iterable object.

play06:47

An iterable object is anything that you can loop through.

play06:49

So something like a string, a list, a tuple, something like a set.

play06:54

It works for all of those.

play06:56

So let's have a look at a quick example.

play06:57

So let's say that

play06:58

what we want to do is

play06:59

we want to get the length of all of the different strings in this list.

play07:03

Well we could iterate through every single one of these strings, manually

play07:07

apply the length function, and then just print it out or store in a new list.

play07:11

But instead we can actually use the map function that does all of this for us.

play07:15

So I can say the length is equal to and then I can use my map function.

play07:20

And the first thing I pass to the map function is the function that I want

play07:23

to apply to all of the different items in my iterable.

play07:26

So in this case, I pass the Len function.

play07:28

We can pass our own function or in this case a built in one in Python.

play07:32

And then I pass the iterable that I want to apply this to which is strings.

play07:35

Now what I can do is I can print out and I need to convert this to a list

play07:39

because again this is going to return an iterator.

play07:41

So it's going to return a map object.

play07:43

If we want to see all of the results then we need to first convert it to a list.

play07:46

And now if I run my code you see that it gives me the length

play07:50

of all of these different items.

play07:52

So it simply took this function, applied it to every single item

play07:55

that was in this list, and then gave me that result inside of,

play07:59

in this case, a new list or really a new iterable that we converted to a list.

play08:03

Now in this case we used a built in function in Python,

play08:06

but we can also use a custom function that we write ourself.

play08:10

Now it's common here to use what's known as a lambda function.

play08:13

A lambda function is a one line anonymous function

play08:16

where you can do something like lambda.

play08:18

You can pass a parameter. In this case it will be x.

play08:20

And then if we want we could do something like x plus s.

play08:25

Now what this is going to do is, is going to pass

play08:27

every single one of the strings to this function as the parameter x.

play08:30

And we're simply going to add an s to all of these different strings.

play08:34

So now what I'm going to do is write run this code.

play08:36

Sorry.

play08:37

And you can see we get an S tacked on to every single one of these strings.

play08:40

Now if you don't want to use a lambda function you can define your own functions.

play08:43

So we can say add underscore s.

play08:45

We can take in our string okay.

play08:48

And then we can say something like return and then string plus s.

play08:53

And now we can just put the name of this function.

play08:55

Notice I'm not calling it I'm just putting it as the name.

play08:59

And then when I run this you can see that we get the exact same result.

play09:02

So that is map.

play09:03

It is extremely useful. Again you pass the function.

play09:06

You pass the iterable object.

play09:08

And then it will apply this function

play09:10

to every single item and give you all of the results.

play09:12

So now we're moving on to the next function which is the filter function

play09:16

which is closely related to the map function.

play09:18

The way the filter function will work

play09:20

is it will take every single item in our iterable object.

play09:24

It will pass it to some function.

play09:26

In this case it's called the filter function.

play09:28

And if that function returns true,

play09:30

it will keep that item, otherwise it will remove it from the result.

play09:34

So let me show you an example.

play09:36

We'll just say filter is equal to.

play09:38

And then we're going to use filter.

play09:40

Same thing. We're going to pass our function.

play09:41

In this case I'm going to pass this custom function I wrote called longer than four

play09:45

which just returns true if the length of a string is greater than four.

play09:49

And then I am going to pass by iterable which is strings,

play09:53

and we are going to print out the list

play09:56

of our filtered okay.

play09:59

So let's spell that correctly.

play10:01

And let's run our code.

play10:02

And notice that we only get World and Apple.

play10:05

The reason for

play10:05

that is what really happens here is we take every single one of our items.

play10:08

So we start with mine. We pass it to this function.

play10:11

This function returns false because my is not a length greater than four.

play10:16

We pass world.

play10:17

We return true because this is length five.

play10:19

Same thing with Apple like five pairs length four.

play10:22

So it's not greater than length four. So we don't include it.

play10:25

So we end up with world and Apple.

play10:27

Obviously this is a very simple function.

play10:29

We can write very complex functions.

play10:31

And this allows us to filter in iterable

play10:33

object based on some function which can be very very useful.

play10:37

Mess around with this.

play10:38

And also remember that you can use the lambda function as well.

play10:41

So we could have written it like this lambda x.

play10:43

And then we could say Len x is greater than four.

play10:47

And to prove that to you if we type this correctly

play10:51

and we run the code, you see that we get the exact same result.

play10:56

So the next function to look at here is a simple one.

play10:58

And this is the sum function.

play11:00

The sum function is simply going to return the sum of all of the different numbers

play11:04

that you pass it from some kind of iterable object.

play11:07

In this case, we're passing an iterable, which is a set.

play11:09

We could pass a list.

play11:10

We could pass a tuple.

play11:11

Doesn't matter so long as the values inside of the iterable are numbers

play11:15

if they are not numeric, so not an int or a float,

play11:18

then you are going to get some kind of error so quickly.

play11:20

We can run the code here, and you can see that we get the sum of 35.5.

play11:24

Now one thing you might not know about the sum function

play11:26

is that you can actually pass to this a start value.

play11:29

So we can pass a start of say ten.

play11:31

And now we will start summing at ten.

play11:33

So now you'll see we get 45.5.

play11:35

Now of course we can make this a negative value as well.

play11:38

So let's go ahead and do that.

play11:39

And you can see that this works perfectly fine.

play11:41

Now the next function on my list is the sorted function.

play11:44

Now this is pretty straightforward.

play11:46

This is going to sort and iterable object in ascending

play11:49

or descending order depending on what we tell it.

play11:52

Now in this case we just have a bunch of different numbers.

play11:55

By default it's going to sort this in ascending order.

play11:57

So if I run the code here, you can see that we get these numbers sorted in

play12:01

ascending order.

play12:02

Now there are a few different arguments

play12:04

that I can pass to this sorted function to change its behavior.

play12:07

For example, I can pass reverse.

play12:10

If we spell this correctly equal to true.

play12:12

And then when I run my code here, you can see that

play12:14

we actually get all of the values in reverse order.

play12:17

But another more interesting argument we can pass here is a key.

play12:21

Now the key will actually be a Python function.

play12:23

And we will apply this Python function to every single item inside of our iterable.

play12:28

And we will sort the items based on what's returned from the key function.

play12:32

Now I'm going to show you a better example of this.

play12:34

So stay with me for one second.

play12:36

Okay, so I just created a better example here so you can see how this works.

play12:39

So I have a list of people.

play12:41

And notice

play12:41

that if I try to sort this list of people we just have Python dictionaries here.

play12:46

And the sorted function isn't really going to know how to sort this.

play12:49

It will do some kind of sort for us, but it's going to be pretty unpredictable.

play12:52

So instead what we do is we pass this a key.

play12:56

Now this key is a lambda function.

play12:58

We take in one argument.

play12:59

In this case it is person.

play13:01

And in this case we get access to the person's age.

play13:04

So what we're doing

play13:04

effectively here is we're sorting these people based on their age.

play13:09

So now when I run the code here and we print this out, you can see that

play13:13

we get all of the people sorted in ascending order based on their age,

play13:17

because we're sorting all of the different items using this key.

play13:21

Now, if we wanted to go a step further, we could reverse this as well.

play13:24

And now we could sort this in ascending or descending order.

play13:27

And you can see we can start with the oldest person and go to the youngest.

play13:31

Moving on the next function to show you is enumerate.

play13:34

But in order to see the value of enumerate, we first have to look at what happens

play13:37

when we don't use it.

play13:39

So oftentimes when we're iterating with a for loop, we want to have access to both

play13:43

the index and the value when we're looping through something like a list.

play13:47

In this case you see that I create a simple for loop.

play13:49

I say for index in range, and then the length of tasks.

play13:52

And then I use that index to access the task that's at that specific position.

play13:56

I then print out index plus one and then the task.

play13:59

And this gives us kind of a nice list.

play14:01

So if we run the code here

play14:02

you can see that we get a list of all of our various tasks.

play14:05

Now this is fine. There's nothing wrong with this code.

play14:07

We can clean it up quite a bit by using the enumerate function.

play14:11

And this is helpful again

play14:12

when you want the index and the value iterating through some kind of iterable.

play14:16

So what I'm going to do is change this here to use enumerate.

play14:20

And I'm going to enumerate over tasks.

play14:22

Now when I do that the first value that I'm going to have access access to here

play14:26

sorry is the index.

play14:27

And the next value will be the task.

play14:29

So what enumerate will really do is it will return to me a tuple,

play14:32

a tuple for every single object where the first object inside of

play14:36

that tuple is the index and the second object is the value.

play14:40

So now what I can do is I can clear this and I can run.

play14:43

And you see we get the exact same thing.

play14:45

So again first variable is going to be the index.

play14:47

Second value is going to be whatever the value actually is.

play14:51

And we can use that for enumerate.

play14:53

Now it's also worth noting that we don't need to use enumerate just in a for loop.

play14:56

If we print out, for example, the list representation of enumerate,

play15:02

you will see what we get.

play15:04

And it is a tuple where we have the index first and then the value,

play15:07

index value, index value, etc..

play15:10

So moving on.

play15:11

The next function on my list is the zip function.

play15:14

But in order to understand the value of using the zip function,

play15:17

we first have to see what it looks like when we don't use it.

play15:19

So in this case you can see we have two lists, right?

play15:21

We have names and we have ages.

play15:23

Now these have corresponding values.

play15:26

So the name at position zero corresponds to the age at position zero.

play15:29

In the other list.

play15:31

So what I'm doing here is I'm looping through

play15:33

both of these lists at the same time.

play15:35

And then I'm printing out. Name is age years old.

play15:37

I'm essentially

play15:38

combining these two values together and using them in some kind of expression.

play15:42

Now notice that what I had to do here with my range is I had to get

play15:45

the minimum length of the names and the ages list.

play15:48

The reason why I had to look for the minimum

play15:50

is because if we have an extra age or an extra name,

play15:53

then we'll get an index out of bounds exception

play15:56

when we try to access the corresponding position in the other list.

play16:00

For example,

play16:00

if we add another name like Tim here, and we don't have a corresponding age

play16:04

when we look for the age at that index, if we were just looping

play16:07

through the length of names, then we're going to get an error.

play16:09

So I have to look at the minimum.

play16:11

Okay.

play16:12

So when I run this code you can see that we get all of the different

play16:15

kind of printed out statements here.

play16:16

Alice is 30, Bob is 25, etc..

play16:19

And this is fine.

play16:19

Again, nothing wrong with this code, but let me show you how much easier

play16:23

it is for us to actually execute this using the zip function.

play16:26

So I'm going to paste this in here.

play16:28

And you can see that now we're using the zip function.

play16:30

Now what the zip function will do

play16:32

is combine different iterable objects together and automatically handle

play16:36

when one iterable object has more objects than the other.

play16:39

So in this case, what's going to happen is is going to combine our names

play16:42

and ages into actually a list of tuples.

play16:46

And then this allows us to loop through them really easily.

play16:49

So let me just run this. You can see how it works.

play16:51

And then we can break it down more in depth.

play16:53

So first let's print out what the zip actually looks like.

play16:57

So I'm going to say print combined.

play17:00

And you can see when I do that we actually get a bunch of different tuples right.

play17:04

So we get the name.

play17:05

Then we get the age name age name age.

play17:07

And notice it didn't include ten because we didn't have a corresponding age.

play17:11

Now if we wanted to go a step further, we could actually include another list.

play17:14

So we could have maybe a gender.

play17:15

And we have female male and then male.

play17:20

And now notice if I add my gender in here,

play17:23

and then we add gender here and we go

play17:26

and is gender when we print this out, you'll see that

play17:31

we're only going to get three lines this time.

play17:32

And that's because the minimum length of all of the different lists

play17:36

we had was three.

play17:37

So it can combined as many different intervals as we want

play17:40

and automatically handle when we have a mismatch number of them.

play17:43

So again we get Alice, 30 female Bob 25 male Charlie 35 male.

play17:48

And then we can print all of this out.

play17:49

ZIP is super, super useful.

play17:51

I use it all the time, and I'd highly recommend

play17:53

you use it in your code as well, especially

play17:55

when you have corresponding values in multiple different iterable objects.

play17:59

So now we move on to the final function on my list, which is open.

play18:03

Now open can be used to open a file read to it right from.

play18:06

It has a lot of different usage.

play18:08

And let me explain to you how to properly use it.

play18:10

So first let's create a variable called file.

play18:12

And we'll use the open function.

play18:14

And the first argument we pass to open is the file name we want to open.

play18:17

So I'm going to go with test dot.

play18:20

Now the second option is going to be the file mode.

play18:23

There's a lot of other options as well as you can see here.

play18:25

And there is a lot of different modes.

play18:27

Now the most common modes

play18:28

that you're going to need to know about are going to be R, which stands for read,

play18:32

which stands for right, and then A, which stands for a pet.

play18:35

Again, there's a lot of other options,

play18:37

but these are the three main ones you want to know.

play18:39

Now for now we're going to go with W because we want to create a new file.

play18:42

And when you use W mode this is going to override a file

play18:46

if it already exists and essentially clear everything that's inside of it.

play18:49

So make sure you're careful when you use this.

play18:51

So now we've opened our file.

play18:53

What we can do is write to it so we can say file dot right.

play18:57

And when we write we can just write some string.

play18:59

So something like hello World.

play19:00

And if we want to move

play19:01

to the next line in the file we need to make sure we use a back line

play19:04

or a new line character.

play19:05

Sorry and say hello world.

play19:07

My name is Tim. Like that.

play19:10

So now if I run my code, you'll see that a new file is created

play19:14

and we have Flow World.

play19:14

My name is Tim.

play19:16

However, it's very important that after we create this file,

play19:20

we write to it that we close it.

play19:22

So we need to actually say file dot close just to make sure

play19:26

that we don't have any memory leaks.

play19:27

And we don't leave the file open in memory when we actually don't mean to do that.

play19:31

Now, in this case, everything's fine if we don't actually close it,

play19:35

but we just want to make sure that we do close closing,

play19:37

if that's actually why, I'm going to recommend

play19:39

that when you are working with files, rather than manually opening

play19:43

and closing them like this, you use the syntax which is the following.

play19:47

Now this is the with the syntax.

play19:48

So you're going to say with open.

play19:51

And then again we can go our test

play19:53

dot txt put our mode as w and we can say as.

play19:57

And then in this case of file.

play19:59

And then we can say file dot right.

play20:01

And whatever we want to right here.

play20:04

Okay. That's great.

play20:06

And now anything that's indented will happen inside of this context manager.

play20:10

That's what this is referred to.

play20:11

And as soon as we exit this or as soon as we finish our operations, it's

play20:15

automatically going to handle closing the file for us.

play20:18

So this is the best practice when it comes to working with files

play20:21

rather than opening and closing them yourself.

play20:24

You always use a context manager which will ensure that the file

play20:27

is always closed properly, even if an error occurs

play20:31

inside of the kind of lines where you're trying to manipulate the file.

play20:34

So just make sure you do that.

play20:36

Anyways, we have the mode, so we have

play20:38

we have our

play20:39

and if we use our mode this allows us to actually read the contents of the file.

play20:44

So to do that we can say file dot read.

play20:46

And if we read this we will get all of the text inside of here.

play20:50

So we can say print and then text.

play20:53

So let's print that out and you can see hello world.

play20:56

My name is Tim gets printed.

play20:58

And then if we want to we can also append to a file.

play21:01

Now appending to a file is not going to override it.

play21:03

It's simply going to add to the end.

play21:05

So if you want to keep adding to the end of a file rather than replacing the contents

play21:09

inside of it, then you use the append mode.

play21:11

Now what we can do is say file,

play21:16

dot, write and do additions like that.

play21:20

And if we run the code here and we open this up,

play21:22

you can see that we have the new addition getting added.

play21:25

And we're just going to get added at the end of wherever the file was.

play21:27

So in this case we didn't have a new line character.

play21:29

So it just gets smushed to this line.

play21:31

If you wanted it to be on a new line,

play21:33

then you would need to add the new line character like that.

play21:36

Now there are also combination modes.

play21:38

So for example, you can do something like

play21:41

mode right where you're reading and you're writing to the file.

play21:44

You can have like a mode.

play21:46

I think that's probably a mode. I'm not sure if that's actually a valid one.

play21:49

Reading and appending and there are all kinds of other modes

play21:51

that you can look up, and you can even ask ChatGPT to tell you it.

play21:55

Just too many for me to cover in this video.

play21:57

Anyways, with that

play21:58

said, that is going to cover the ten Python functions that you need to master.

play22:01

I hope you found this video helpful.

play22:03

If you did, make sure to leave a like.

play22:05

Subscribe to the channel and I will see you in the next one.

Rate This

5.0 / 5 (0 votes)

Related Tags
Python FunctionsProgramming TipsCode MasteryPrint FunctionHelp FunctionRange IteratorMap ApplicationFilter LogicSum AggregationSorted OrderEnumerate LoopZip CombiningOpen FileDeveloper GuideCoding TutorialEducational Content