Python Basics You Should Know! - Part 1

Python Basics You Should Know! - Part 1


Remove elements in the List while Looping

first we will show you what NOT to do: NEVER loop over a list and remove elements at the same time! it will lead to an error.

for example: in this program, we loop over a list and want to remove every even number and we have an even function that returns true if the number is even. we can see that the result still has a number 2 in .. IT IS NOT CORRECT!


a=[1,2,2,3,4]
def even(n):
? ? return n % 2 == 0


for item in a:
? ? if even(item):
? ? ? ? a.remove(item)
print(a) # The Result : --> [1,2,3]        

the mistake in this code is that we removed the element while looping over it so then all elements got shifted one place to the left and as a result, we skipped one iteration.


The correct way to do this is to loop over a copy of the list. the tiny difference here :

for item in a[:]: # <---- Hello, I'm the tiny difference
? ? if even(item):
? ? ? ? a.remove(item)
print(a) # The Result : --> [1,2,3]        

This is called list slicing and with this syntax, we create a copy of the list & can modify the original list.

?another solution is to just create a copy and put in all elements that don't meet the condition.

The code will be like this :

a=[1,2,2,3,4]
def even(n):
? ? return n % 2 == 0
print(a)
a= [k for k in a if not even(k)]
print(a)        

We can see that we solve it with list comprehension syntax.

one more tiny change which makes the copy process a little bit more efficient is the following change to the one-line code :

a[:]= [k for k in a if not even(k)]        

Here we assign the values to the slice of the list and modify the list in place.

We see the result is the same but it's a little bit faster than assigning the whole list.

No alt text provided for this image


Check if a file/directory exists

First of all, instead of checking if the file exists, it's good directly open it and wrap everything in a TRY Except BLOCK.

This strategy is also known as easier to ask for forgiveness and permission and it's a perfectly accepted python coding style. if we don't want to raise an exception or we don't need to open a file and just need to check if it exists to you, then you have a different option:

import os


if os.path.isfile("main.py"):
? ? f = open("main.py")
? ? print("Yes1")


if os.path.isdir("venv"):
? ? print("Yes2")


if os.path.exists("venv"):
? ? print("Yes3")
        



#1 os.path.isfile -> it returns true for valid file
#2 os.path.isdir -> it returns true for valid directory
#3 os.path.exists -> it returns true for valid file OR directory

        

With python 3.4 you can also use the pathflip module which offers an OO approach to work with file system paths and this is a great way of dealing with files & directories. You can create a path object like this and now we can use the different methods on the path object.

Find the index of an item in a list

To find the index, you can simply use {listname}.index and it returns a 0 based index in the list of the first item whose value is equal to X if there is no such item it raises a value error.


listname = ["Apple","Facebook","Google"]


listname.index("Apple") # place 0
listname.index("Facebook") # place 1
listname.index("Google") # place 2


listname.index("Linkedin") # ValueError: 'Linkedin' is not in list - Sorry Linkedin ?        

In order to deal with the possible exceptions, you can wrap everything in TRY Except BLOCK. for example: assign -1 to the index in case it's not there. also that it only returns one index of the first match.


listname = ["Apple","Facebook","Google"]
try:
? ? ?ind = listname.index("Linkedin")
except ValueError:
? ? ind = -1        

So, if there are multiple items of the same value and we want to get all indices, we can do it using comprehension where you loop over the whole list :

listname = ["Apple","Facebook","Apple"]


listname.index("Apple") # place 0
ind = [i for (i, e) in enumerate(listname) if e == "Apple"]
print(ind) # place 0 & 2        


Merge two dictionaries with Python

With python, we have an UPDATE function that updates the dictionary with the key-value pairs from other overriding existing keys. however, it modifies the original dictionary in place instead of returning a new one.


a = {'a':1, 'b':2}
print(a) # {'a': 1, 'b': 2}


b = {'b':8, 'c':9}
print(b) # {'b': 8, 'c': 9}


a.update(b)
print(a) # {'a': 1, 'b': 8, 'c': 9}        

If we want to create a new dictionary with the MERGE KEY VALUE PAIRS, we should use different methods depending on which python version we use.?

Since Python 3.9 we can use the single vertical bar or pipe sign:


a = {'a':1, 'b':2}
print(a) # {'a': 1, 'b': 2}


b = {'b':8, 'c':9}
print(b) # {'b': 8, 'c': 9}


a= a | b
print(a) # {'a': 1, 'b': 8, 'c': 9}        

Since Python 3.5 we can use the syntax which is known as dictionary unpacking - like this :


a= {**a, **b}
print(a) # {'a': 1, 'b': 8, 'c': 9}        

for sure, with the lower versions we should use the copy Function:


a=a.copy()
a.update(b)
print(a) # {'a': 1, 'b': 8, 'c': 9}        
No alt text provided for this image


Concatenate two lists in python

The Simplest Way to combine two lists is using the + OPERATOR!


a = [1, 2]
b = [3, 4]


c = a + b
print(c) # [1, 2, 3, 4]        

#another_alternative is the following code :


a = [1, 2]
b = [3, 4]


c = [*a, *b] # <--- weird one!
print(c) # [1, 2, 3, 4]        

We can use it since py 3.5. This is a more general way to unpack and combine items, for example :

if b is a Tuple - so for the + OPERATOR we will get an error because we can't use the + OPERATOR for a List in the tuple;


a = [1, 2]
b = (3, 4)


c = a + b
print(c) # Error!        

However, the unpacking syntax works for different types of iterables.. So the following code will be run :


a = [1, 2]
b = (3, 4)


c = [*a , *b] # unpacking syntax : i love you,iterables!
print(c) # [1, 2, 3, 4]        


I hope you enjoyed these basics, See you soon. ??♂?


Jamil Nakhleh.




Amichai Oron

I Help Tech companies transform their vision into paying products. Proven success with $100M+ Industry Leaders, Align your product with customers and investors in 90 days

1 周

???? ??? ?? ?? ???????? ??? ????? ???? ?????? ???: ?????? ????? ??? ??????? ?????? ??????, ?????? ?????? ??????,?????? ????? ????????. https://chat.whatsapp.com/IyTWnwphyc8AZAcawRTUhR

回复
Noam Schwartz

?????? ?????? ?????? ?? ?????? ?????? ?????? | ?????? ?????? ??????? ??????? | ????? ?????? ????? ??????? ???? | ?????? ????? ??????? ?????? ?????? ??????? ??????? ??????? ??????? ??????? ?????

2 个月

???? ??? ?? ?? ???????? ??? ?????? ???? ?????? ???: ?????? ????? ??? ????? ?????? ?????? ??????. ?????? ?????? ?????? ?????,??????? ??????? ???????: https://chat.whatsapp.com/BubG8iFDe2bHHWkNYiboeU

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了