Python Tips and Tricks

Tech With Tim · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

The video covers various tips and tricks in Python, including the use of enumerate, string multiplication, variable swapping, and list comprehension, to help programmers save time while coding. It also discusses the help function, dir function, and IDE functionality.

Full Transcript

hey guys and welcome back to another YouTube video so in today's video I'm going to be showing you some cool tips and tricks um that you can use in the Python programming language now most of these T tips are very specific to Python and you probably don't even know they exist um but they are definitely going to be able to save you a lot of time programming and they make things a lot easier so one of the great things about the Python language is it has a lot of built-in functions methods um even modules that you can use to help you program and it's built um around all of the things are wrong with other programming languages essentially um so a lot of these tricks that you have in here you probably don't even know exist and can save you a ton of time and a ton of work so go ahead and make sure you watch through the whole video as I'm going to be going through eight tricks um in this one I'm going to do a part two video later on um but these tricks will save you a lot of time and when I found out about them uh I was very excited um because I no longer had to go through rigorous coding um to perform somewhat simple tasks so let's get ahead and get started and this first one um kind of solves a problem uh that a lot of programs will run into if you're trying to well solve problems so what you want to do is you want to have the index of a list and you also want to have the element in that list so I'm just going to write a list here to start uh in this case I'm just going to do a b and c very simple for the purpose of the example now what you would want to do essentially in a for Loop is you'd want to have well the index of the item but you also want to know what the item is so what you typically would write is something like this you'd say 4X in um and let's say or actually we're going to start we're just going to make another variable here we're just going to say counter equal Z we're going to say 4X in Li and then what you do is you'd increment counter plus equal 1 every time you run the for Loop um and I could be print for example a counter and X um so that you could know what index your elements at um I'm just going to move this actually below print because that doesn't make sense what element your uh is like the index for your element and then you also want to know what the element is um so I'd print them here so I'm printing the counter and then I'm printing X so you can see if I run program I get 0 a 1 b 2 C now that's great but you had to use this counter variable what python does it actually allows you to do this without using this counter variable and to shorten it up a little bit so I'm going to show you how we do that here so F first of all it goes for I and then item in and now this is the keyword enumerate like that okay and then you just put your list name here so in this case Li and now what it's going to happen is I is going to be assigned the index of your element so in this case when we're going through first it's going to be assigned zero for a item is going to be assigned to a so now you have both of them with two separate variables and you didn't have to make this counter variable so I'll show you how it works now again we'll print I and then item like that see if we run the program we get the same thing and we just shortened up two lines we no longer need a counter variable and we no longer need to well Define that or increment it at top so that's really really useful you're going to notice you use this a lot especially when you're trying to solve problems so that's a really cool one um the next one I'm going to talk about and um a lot of you probably will know this but this is really cool as well especially if you're trying to print stuff to the console is you can actually do something called string multiplication in Python now it seems weird in most cases you can only add strings together called concatenation um but you can actually multiply them in Python so I'll show you an example I have a string like hello if you wanted to print this string like four times to the screen in other languages what you do is you do something like this plus s um oh I have a capital S at the end there oops so let's just print it four times and you get hello hello hello right but what if you wanted to print this 100 times you don't want to constantly keep adding maybe you go through a for Loop to add all the s's together anyways in Python it's a lot easier all you have to do is s multiplied by and then an integer in this case I'm going to do four and I get hello hello hello hello so that's really cool you can multip strings together uh and that's another useful trick in Python so the next one is a variable Swap and this one you'll use a lot especially if you solve um I don't know if you solve a lot of problems do like programming exercises and stuff where you want to change two variables around so you want to change um I don't know you want to change a to equal B and B to equal a now what you would typically have to do and I'll show you here um in any other programming language is what you want to do is you're going to have to go temp you're going to have to make a temp variable you're going to say temp equals a AAL B and Bal a like that so now you've effectively changed a to be B and you've changed B oh so see this I've even made a mistake here this should not be a should b equals temp because after you change a now it's equal to B you still want the value of a so you're going to have to call that temp variable here that we just created so b equals temp so I'm just going to do this so that we can kind of see a little bit better okay so now what you want to do um in Python is it actually makes it a lot easier here so what you can do is you can just go a comma Bal B comma a now this looks really weird in any of the programming languages probably give you an error but this actually works fine so you can say AAL B and B equal a now I'm just going to do it one more time because since we already changed b and a up there they're going to be different and then I if I print to the screen or I just go a you can see it's equal to two and I print B it's equal to one so we had two and one up here um but then by running this line it actually changed them around and just the reason ran it twice in case you didn't understand it's cuz I changed it up here I just wanted to change it back so you could see from my original variables okay next trick um and this one is kind of a similar trick and it's you can actually assign multiple variables to um the value of a list so for if I'm just make a new list I'm just going to say Li I equals let's just go yeah a b and c once again now I can do something like this which looks really weird but actually works fine xyzal Li now if I print X I get a print B oh B sorry print y I get B and I print Zed I get C so by just running these three variables here it assigns to the same uh the ones corresponding in the list which again in any other programming language you think is like what the heck you can actually do that but yes that is something you can do now I'm just going to restart this idle cuz I don't like working at the bottom bottom of it I want it to be easier and you can see at the top so the next trick that I have here and this is one you might know about um and it's really useful if you're trying to use like someone's else's modules or you want to figure out what a function does without having to look it up um and it's called The Help function now it seems like oh why would I need to use this um but it's actually extremely useful so you can call this on any function so for example I call help on the function Len then you see we get help on built-in function Len in module built-ins it says length it gives you the parameters so we need an object and then it returns a number of items in a container and that tells you what that does so if I go help on function range for example then it goes through all the stuff that the range function does that you probably didn't even know so it runs through the pretty much the dock string of this function um and it tells you all the things that you can do with um well with that function so I'm just going to open it again because I don't like working at the bottom I'm sure there's a way to clear it but I don't really know so uh we're just going to do this for now the next one um is similar and this one is actually called dur now what this is going to do is is actually going to list all of the methods um that you can use on a certain class so for example the class string has a ton of different methods like dot um I don't know what's a string method do strip uh something like that right uh uper do lower so if you run this it prints all of the different methods that exist on this class so we have R strip split split lines and then if you don't know what one of these does you can just go ahead and call the help function on that so you do I think it's like Str Str and then Dot and then whatever one you want so it's R split well that should give us something maybe let's see yeah so then it says help on the method um and it goes through and tells us exactly what our split does and that's really useful okay the next trick in Python um and this is pretty well known but I just wanted to show it in case some of you guys didn't know it it's called list comprehension and it's a way to create a list within one line um without having to use a for Loop so I'll show you what I mean here so what you can actually do is you can do something like Li and that just stands for list by the way and I'm going to say is equal to X for x in range 10 if x modulus 2al equal Z and now I'll break this down on what this actually does for us um so it's going to say the list is equal to X so an element x 4 x in range 10 so now what this is going to do is it's going to run x 10 times so 0 to 9 and now I'm just saying I'm only going to add this element X if it's divisible by two so if it's an even number pretty well um um and I'll just show you if I print li like this get 0 2 4 6 8 and you can do this with multiple statements you can change this around so for example I could say one for X in range 10 now if I just wanted to create a list of ones so 10 ones then that's what I'm doing here I get one one one1 one one and so on like that so that just because I didn't say Li equals it just gave me that list um you can see how that works and you can do multiple lists you can you can do a list inside of the list so you say 4X in range let's see oops messing up my typing here and then we get five empty lists inside of another list and that's really useful in Python um because in other languages if you wanted to create a list you'd have to do something like forx in range 10 and then you'd have to do list do append and so on so this is going to crash just cuz you can't use lists like that um but anyways then you have to append to the list and that means you need at least three lines cuz you have to create the list up there whereas in Python you can just do it in one um and that saves a lot of time so the last two that I'm going to get in here into here are um just some functions that you can use on strings which are really really useful and they save a lot of effort so I'm just going to copy a list that I've already have typed out here just to save us some time let me say hello ABC so on just a bunch of random words and letters and now there's a function called reversed in Python now what this allows us to do is pretty well just reverse the list so I'm going to say reversed Li and then if I it's cuz I didn't print it to the screen my bad reversed Li H interesting why this isn't working H I have to do this it's because it's an object print list reversed Li and this should work there we go so now we get a list that's reversed uh and so it was Tech Tim and so on like that what was happening here is I was literally just printing the actual function um I wasn't converting it into a list so yeah um that's why that wasn't working so anyways reversed Li it reverses the list next one is going to be sorted so I'm going to do the same thing here so I'm just going to say print sorted and I'll just put a list around it in case this gives gives us an error again and then I'm going to sort that list that I have up there so I'm going to say sort Li and there we go now we get a sorted list based on alphabetical order now with the sorted function you can actually use um something called keys which are again really useful so I'm just going to do the same thing here print this again um and in this sorted function I'm just going to do a comma and I'm going to say key is equal to Len now I'll give you a second to guess what this is going to do just think about it if I add something called key equals Len you might be kind of confused but think at what this might give us so I'm going to run the function and you can see now it actually gives us a list not sorted alphabetically but sorted by length so we go shortest to longest and again say you wanted it to go longest to shortest then you could um just reverse this list using the Reversed function and you would get that sorted list in the opposite order okay so now the last one that I'm going to show you um is this cool thing that you can do in ide you might have seen me use it once so pretty much when we're ever running something in the console I want to save some time um we don't want to keep using copy paste if you put your cursor on any line in here so for example I'm going to go print uh and just before right after the arrows and then you just click enter it's actually going to copy whatever was on that line so after your cursor onto the next uh like the next running line in the uh editor which is really useful um if you're trying to run the same thing over and over and test a program or just change like the argument so you don't have to keep typing it or copying and pasting and another thing that you can do is you could do something um and this is kind of goes with that is if I just click underscore like this uh it's going to actually give me the last output uh here so let's do a better example I do a equals F and I just do a it gives me f like that right now if I just type in underscore and hit enter it gives me the last output that I got from my uh from my console here from my like idle whatever you're running so again if I do something like b equals four and I just type B and then I do an underscore it's just going to print simply what we just last had um I don't know why that's useful but it's something that's cool I didn't say all these uh tricks were super useful um but that's just another cool one that you can use like that so anyways that has been it for uh part one of this tips and tricks video in python in the next one I'm going to go over some more advanced tips and maybe some more useful tips these ones are kind of like the generic ones the cool ones people typically learn when they first start out in Python the next ones I'm going to be using collection types uh and these ones are seriously going to save you a lot of time so make sure you look out for that video um if you're more advanced with python and you already knew some of these tricks anyways um I hope you guys enjoyed the video if you did please make sure you leave a like And subscribe and I will see you again in another one [Music]

Original Description

THESE WILL SAVE YOU A CRAZY AMOUNT OF TIME! In this video I go over different tips and tricks in python that are sure to save you a lot of time while programming. Python was created on the basis of all things that are wrong with other programming languages; this explains why this language has so many helpful tools. Most of the tips and tricks shown are specific to python. List of Tips and Tricks: #Python cool tricks #1 - Enumerate li = ['a', 'b', 'c', 'd'] for x in range(len(li)): print(li[x]) for i, item in enumerate(li): print(i, item) #2 - String multiplication s = "hello" print(s+s+s+s) print(s*4) #3 - variable swap a = 1 b = 3 temp = a a = b b = temp a,b = b,a #4 - variable assignment from list a = [1,2,3] x,y,z = a #5 - help() function help(len) #5 - dir() function dir(str) #6 - list comprhension li = [x for x in range(10) if x%2 == 0] #7 - Sorted and reversed li = ['hello', 'abc', 'abcd', 'goodbye', 'name', 'tim', 'tech'] reversed(li) sorted(li) sorted(L, key = len) Want To Support This Channel? Bitcoin: 1PbkAYLFaJBgjbKn2ptGyBz65xWN8hJgBU Ethereum: 0xdd42dbbdba60f7163fc7a840e189474b6e8bfcad Ripple: rD4arM9CVjQWqi8f1kxdpCgkCgEkqBgtud Please leave a LIKE and SUBSCRIBE for more content! Tags: - Tech With Tim - Coding - Pygame - Python Tutorials - Python Tips and Tricks - Python tips - Python tricks - Python tips and tricks for beginners
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video teaches various tips and tricks in Python to help programmers save time while coding. It covers topics such as enumerate, string multiplication, and list comprehension, and provides practical examples of how to apply these concepts. By watching this video, viewers can improve their Python skills and write more efficient code.

Key Takeaways
  1. Use enumerate to get index and element in a for loop
  2. Use string multiplication to repeat a string
  3. Swap variables using a comma-separated list
  4. Assign multiple variables to a list
  5. Use the help function to get information about a module or function
  6. Use the dir function to list methods of a class
  7. Create a list using list comprehension
💡 Using tips and tricks in Python can significantly improve coding efficiency and reduce time spent on programming tasks.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →