Please Master These 10 Python Functions…

Tech With Tim
7 Jun 202422:16

Summary

TLDRこのビデオでは、Pythonのプログラミングにおいて習得すべき重要な10の関数について解説します。基本的なprint関数から始まり、help関数、range関数、map関数、filter関数、sum関数、sorted関数、enumerate関数、zip関数、そしてファイル操作に使うopen関数まで、各関数の使い方とその応用例を詳しく説明します。また、各関数の追加引数や便利な使い方も紹介しています。このビデオを通じて、これらの関数をマスターすることで、Pythonプログラミングの効率が大幅に向上するでしょう。

Takeaways

  • 📝 Pythonの基本的な関数として、`print`関数が紹介され、その引数`sep`と`end`を用いた高度なフォーマット方法が解説されています。
  • 📚 `help`関数は、Pythonの関数のドキュメントを簡単に表示できる便利なツールとして紹介されています。
  • 🔢 `range`関数は、数値の範囲を生成する際に非常に有用で、開始値、終了値、ステップ値を指定できます。
  • 🗺️ `map`関数は、iterableオブジェクトの各要素に関数を適用し、新しいiterableを生成する機能を有しています。
  • 🎭 `filter`関数は、iterableオブジェクトから特定の条件を満たす要素を選択的に抽出する際に使用されます。
  • ➕ `sum`関数は、iterableオブジェクト内の数値を合計し、オプションで開始値を指定できます。
  • 🔄 `sorted`関数は、iterableオブジェクトをソートし、`reverse`や`key`引数を用いてソートの挙動を変更できます。
  • 🔑 `enumerate`関数は、forループでインデックスと要素値の両方を取得する際に便利です。
  • 🔗 `zip`関数は、複数のiterableオブジェクトをタプルのリストに結合し、同時に複数のリストをループする際に非常に有用です。
  • 📖 `open`関数は、ファイルを開いて読み書きする際に使用され、ファイルのモードやコンテキストマネージャーの重要性が強調されています。

Q & A

  • Pythonで最初に学ぶことは何ですか?

    -最初に学ぶのはprint関数です。基本的に画面にメッセージを表示するために使用されます。

  • print関数で使用できる追加の引数は何ですか?

    -print関数ではsep引数とend引数を使用できます。sep引数は区切り文字を指定し、end引数は行の終わりに追加する文字を指定します。

  • help関数の役割は何ですか?

    -help関数はPythonの関数のドキュメントを表示するために使用されます。ドキュメント文字列を読み取って、関数の使い方を教えてくれます。

  • range関数の基本的な使い方は何ですか?

    -range関数は数値の範囲を生成します。開始値、終了値、およびステップ値を指定できます。デフォルトでは0から指定した値までの数値を1ずつ増やして生成します。

  • map関数はどのように使用されますか?

    -map関数は指定した関数を反復可能オブジェクトの各要素に適用します。例えば、文字列リストの各文字列の長さを計算する場合に使用できます。

  • filter関数の使い方を説明してください。

    -filter関数は反復可能オブジェクトの各要素に指定した関数を適用し、関数がTrueを返す要素のみを保持します。例えば、長さが4以上の文字列のみをリストから抽出できます。

  • sum関数の用途は何ですか?

    -sum関数は反復可能オブジェクト内の数値の合計を計算します。開始値を指定することも可能です。

  • sorted関数の主要な引数は何ですか?

    -sorted関数の主要な引数にはreverseとkeyがあります。reverse引数は並べ替え順序を指定し、key引数は各要素に適用する関数を指定します。

  • enumerate関数の利点は何ですか?

    -enumerate関数は反復可能オブジェクトをループする際に、要素とそのインデックスを同時に取得できる利点があります。

  • zip関数はどのように機能しますか?

    -zip関数は複数の反復可能オブジェクトを組み合わせ、それらをタプルのリストとして返します。対応する要素を同時に処理する場合に便利です。

Outlines

00:00

📘 Pythonの基本的な10の関数の紹介

この段落では、Pythonで書かれるコードによく使われる10の関数が紹介されています。これらの関数は単純そうに見えるかもしれませんが、多くの追加のパラメータがあり、時間を節約するのに役立ちます。まず最初に紹介されたprint関数は、文字列や変数を表示するための基本的な関数ですが、Sep引数を用いてデリミタを変更したり、end引数を変更して行の最後に何を表示するかをカスタマイズすることができます。次に紹介されたhelp関数は、Python関数のドキュメントを簡単に取得できる便利な関数です。

05:00

🔢 range関数の使い方とmap関数の紹介

この段落では、range関数の使い方とmap関数の機能が説明されています。range関数はデフォルトでは1から始まり、指定された数値まで(ただしその数値は含まない)の範囲の数値を生成します。また、start、stop、stepの3つの引数を指定して、任意の範囲の数値を生成することができます。逆方向の数値の範囲も生成可能です。map関数は、iterableオブジェクトの各要素に指定された関数を適用し、結果をまとめて返します。組み合わせるlambda関数の使用例も紹介されています。

10:01

🌐 filter関式とsum関数の活用

filter関数は、iterableオブジェクトの各要素に対して関数を適用し、その関数がTrueを返す要素だけを結果として返します。この段落では、文字列のリストから長さが4を超える要素を選択する例が紹介されています。また、sum関数はiterableオブジェクトの数値を合計し、オプションで開始値を指定することができます。

15:02

🔄 sorted関式とenumerate関数の使い方

sorted関数はiterableオブジェクトをソートし、指定に応じて昇順または降順で並べ替えることができます。key引数を用いて、ソートの基準を指定することも可能です。enumerate関数は、forループでインデックスと値に同時にアクセスする際に便利で、タプルの形でインデックスと値を返します。

20:05

🔗 zip関式とopen関数の応用

zip関数は複数のiterableオブジェクトを組み合わせて、タプルのリストを作成します。これにより、複数のリストを簡単にループすることができます。open関数はファイルのオープンや書き込みに使用され、with文を用いることでファイルの自動クローズが保証されます。また、読み込みや追記モードについても説明されています。

📝 ファイルを扱う際のベストプラクティス

最後の段落では、ファイルを扱う際のベストプラクティスが紹介されています。with文を用いたファイル操作が推奨され、エラーが発生した場合でもファイルが適切にクローズされることが強調されています。また、読み込みモードや追記モードでのファイル操作の例も提供されています。

Mindmap

Keywords

💡print関数

print関数は、Pythonで標準出力にメッセージを表示するための基本的な関数です。動画では、複数の引数をカンマで区切って出力できること、そしてsepやend引数を使って出力の形式を変更できることが説明されています。例えば、sep引数を使うことで、出力の間にパイプやカンマを挿入することができます。

💡help関数

help関数は、Pythonの関数やモジュールのドキュメントを表示するために使用されます。この動画では、help関数を使うことで、関数の使い方や引数についての詳細な情報を簡単に得られることが強調されています。例えば、print関数に対してhelpを呼び出すと、print関数のドキュメントが表示されます。

💡range関数

range関数は、指定した範囲内の数値のシーケンスを生成するために使用されます。forループでよく使われ、開始値、終了値、ステップ値を指定することで、複数の異なるシーケンスを生成できます。例えば、range(2, 10, 2)は2から始まり、10未満まで2ずつ増加する数値のシーケンスを生成します。

💡map関数

map関数は、指定した関数をイテラブルオブジェクトの各要素に適用して、新しいイテラブルを生成します。動画では、文字列のリストに対してlen関数を適用して、各文字列の長さを得る例が紹介されています。カスタム関数やラムダ関数も使用できます。

💡filter関数

filter関数は、指定した関数の条件を満たす要素のみを抽出するために使用されます。動画では、文字列の長さが4より大きいものをフィルタリングする例が示されています。ラムダ関数を使用して、条件を簡潔に記述することもできます。

💡sum関数

sum関数は、イテラブルオブジェクト内の数値の合計を計算します。動画では、数値のセットに対してsum関数を適用し、合計値を求める例が紹介されています。また、開始値を指定することもでき、例えばsum([1, 2, 3], 10)とすると、10を開始値として合計を計算します。

💡sorted関数

sorted関数は、イテラブルオブジェクトを昇順または降順にソートします。動画では、数値のリストを昇順および降順にソートする方法、さらにキー関数を使用して辞書のリストを特定のキーに基づいてソートする方法が説明されています。

💡enumerate関数

enumerate関数は、イテラブルオブジェクトをループする際に、インデックスと要素の両方にアクセスできるようにします。動画では、タスクのリストをループして、各タスクにインデックス番号を付けて出力する例が示されています。

💡zip関数

zip関数は、複数のイテラブルオブジェクトを組み合わせ、それらの対応する要素をタプルとして返します。動画では、名前と年齢のリストを組み合わせて、それぞれの名前に対応する年齢を出力する方法が説明されています。また、異なる数の要素を持つリストを扱う際の柔軟性も紹介されています。

💡open関数

open関数は、ファイルを開いて読み書き操作を行うために使用されます。動画では、ファイルを開く方法、モード('r', 'w', 'a')の違い、そしてwith文を使用してファイルを安全に操作する方法が説明されています。特に、with文を使うことで、ファイルを手動で閉じる必要がないことが強調されています。

Highlights

Pythonコードを書く際に重要な10の関数を学ぶことが重要です。

最初の関数はprint関数で、複数の引数を渡すことで動作を変更できます。

sep引数を使って出力の区切り文字を変更できます。

end引数を使って行の末尾に追加される文字を変更できます。

help関数を使って関数のドキュメントを取得できます。

range関数は数値の範囲を生成するのに使用され、forループで頻繁に使用されます。

range関数は開始、終了、ステップ値を指定できます。

map関数はイテラブルの各要素に関数を適用します。

lambda関数を使って一行の匿名関数を定義できます。

filter関数は条件に合致する要素のみを返します。

sum関数は数値の合計を返します。

sorted関数はイテラブルを昇順または降順にソートします。

enumerate関数はイテラブルをループする際にインデックスと値の両方にアクセスできます。

zip関数は複数のイテラブルを一緒に結合します。

open関数はファイルの読み書きに使用され、with文を使うと自動的にファイルを閉じます。

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)

関連タグ
Python関数printhelprangemapfiltersumsortedenumeratezipopenファイル操作プログラミング初心者向けコード解説効率化