1586489820
This video covers some different tips and trick in Python. These tricks make it easier and faster to write python code and give you some good tools to use the future. What’s your favorite python tip and trick? Let me know!
Python is one of the most preferred languages out there. Its brevity and high readability makes it so popular among all programmers.
So here are few of the tips and tricks you can use to bring up your Python programming game.
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
Output:
10 20
20 10
a = "GeeksForGeeks"
print("Reverse is", a[::-1])
Output:
Reverse is skeeGroFskeeG
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
Output:
Geeks For Geeks
n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)
Output:
True
False
import os
import socket
print(os)
print(socket)
Output:
<module 'os' from '/usr/lib/python3.5/os.py'>
<module 'socket' from '/usr/lib/python3.5/socket.py'>
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
Output:
2
1
2
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
Output:
1 2 3 4
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
Output:
4
import sys
x = 1
print(sys.getsizeof(x))
Output:
28
n = 2
a = "GeeksforGeeks"
print(a * n)
Output:
GeeksforGeeksGeeksforGeeks
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
# or without having to import anything
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek'))
Output:
True
False
Python Tricks For Coding More Efficiently: String, List, Dictionary, Matrix, Operators,Initialization
Python is an high level general-purpose language. It’s dynamically typed and garbage-collected. It supports many programming paradigms: procedural, object-oriented, and functional. Historically, Python was conceived as a successor to the ABC language. Python strives to make developers happy by its simpler, less-cluttered syntax and grammar.
In the Zen of Python, highlights from the language philosophy includes:
No wonder Python’s popularity has been growing. According to Stackoverflow blog, the usage is growing more than any other language.
In this article, I have compiled 20 useful Python tricks for the beginner. Whether you’ve just picked up a Python programming book or you have gone through one or two projects, some or all of these tricks may be helpful for your future projects.
a=”new”
print(“Reverse is”, a[::-1])
Output: Reverse is wen
a="Who Are You"
b=a.split()
print(b)
Output: [‘Who’, ‘Are’, ‘You’]
print(“me”*8+’ ‘+”no”*10)
Output: memememememememe nononononononononono
a = [“I”, “am”, “here”]
print(“ “.join(a))
Output: I am here
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
print(is_anagram(‘geek’, ‘eegk’))
print(is_anagram(‘geek’, ‘peek’))
Output:
True
False
import itertools
a = [[1, 2], [3, 4], [5, 6]]
b = list(itertools.chain.from_iterable(a))
print(b)
Output: [1, 2, 3, 4, 5, 6]
a=[“10”,”9",”8",”7"]
print(a[::-1])
Output: [‘7’, ‘8’, ‘9’, ‘10’]
a=[“10”,”9",”8",”7"]
for e in a:
print(e)
Output:
10
9
8
7
a=[‘a’,’b’,’c’,’d’]
b=[‘e’,’f’,’g’,’h’]for x, y in zip(a, b):
print(x,y)
Output:
a e
b f
c g
d h
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[-3:-1]
Output:
[8, 9]
a = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(a), key = a.count))
Output:
4
mat = [[1, 2, 3], [4, 5, 6]]
new_mat=zip(*mat)
for row in new_mat:
print(row)
Output:
(1, 4)
(2, 5)
(3, 6)
a = 5
b = 10
c = 3
print(c < a)
print(a < b)
print(c < a < b)
Output:
True
True
True
dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
dict2={v: k for k, v in dict1.items()}
print(dict2)
Output:
{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}
dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
for a, b in dict1.iteritems():
print (‘{: {}’.format(a,b))
Output:
a: 1
b: 2
c: 3
d: 4
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)
Output:
{‘a’: 1, ‘b’: 3, ‘c’: 4}
a_list = list()
a_dict = dict()
a_map = map()
a_set = set()
#listA contains 1000 0's
listA=[0]*1000
#listB contains 1000 2's
listB=[2]*1000
import sys
a=10
print(sys.getsizeof(a))
Output: 28
x, y = 1, 2
x, y = y, x
print(x, y)
Output:
2 1
Python is a popular, general-purpose, and widely used programming language. It’s used for data science and machine learning, scientific computing in many areas, back-end Web development, mobile and desktop applications, and so on. Many well-known companies use Python: Google, Dropbox, Facebook, Mozilla, IBM, Quora, Amazon, Spotify, NASA, Netflix, Reddit, and many more.
Python is free and open-source, as well as most of the products related to it. Also, it has a large, dedicated, and friendly community of programmers and other users.
Its syntax is designed with simplicity, readability, and elegance in mind.
This article presents 20 Python tips and tricks that might be useful.
The Zen of Python also known as PEP 20 is a small text by Tim Peters that represents the guiding principles to design and use Python. It can be found on Python Web site, but you can also get it in your terminal (console) or Jupyter notebook with a single statement:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
If you need multiple variables to reference the same object, you can use the chained assignment:
>>> x = y = z = 2
>>> x, y, z
(2, 2, 2)
Logical and elegant, right?
You can merge multiple comparisons to a single Python expression by chaining the comparison operators. This expression returns True if all comparisons are correct or False otherwise:
>>> x = 5
>>> 2 < x ≤ 8
True
>>> 6 < x ≤ 8
False
This is similar to (2 < x) and (x ≤ 8) and (6 < x) and (x ≤ 8), but more compact and requires x to be evaluated only once.
This is also legal:
>>> 2 < x > 4
True
You can chain more than two comparisons:
>>> x = 2
>>> y = 8
>>> 0 < x < 4 < y < 16
True
You can assign multiple variables in a single statement using tuple unpacking:
>>> x, y, z = 2, 4, 8
>>> x
2
>>> y
4
>>> z
8
Please, note that 2, 4, 8 in the first statement is a tuple equivalent to (2, 4, 8).
Ordinary multiple assignments are not all Python can do. You don’t need the same number of elements on the left and right sides:
>>> x, *y, z = 2, 4, 8, 16
>>> x
2
>>> y
[4, 8]
>>> z
16
In this case, x takes the first value (2) because it comes first. z is the last and takes the last value (8). y takes all other values packed in a list because it has the asterisk (*y).
You can apply multiple assignments to swap any two variables in a concise and elegant manner, without introducing the third one:
>>> x, y = 2, 8
>>> x
2
>>> y
8
>>> x, y = y, x
>>> x
8
>>> y 2
One way to merge two or more dictionaries is by unpacking them in a new dict:
>>> x = {'u': 1}
>>> y = {'v': 2}
>>> z = {**x, **y, 'w': 4}
>>> z
{'u': 1, 'v': 2, 'w': 4}
If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:
>>> x = ['u', 'v', 'w']
>>> y = '-*-'.join(x)
>>> y
'u-*-v-*-w'
If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate:
>>> for i, item in enumerate(['u', 'v', 'w']):
... print('index:', i, 'element:', item)
...
index: 0 element: u
index: 1 element: v
index: 2 element: w
In each iteration, you’ll get a tuple with the index and corresponding element of the sequence.
If you want to iterate through a sequence in the reversed order, you should use reversed:
>>> for item in reversed(['u', 'v', 'w']):
... print(item)
...
w
v
u
If you’re going to aggregate the elements from several sequences, you should use zip:
>>> x = [1, 2, 4]
>>> y = ('u', 'v', 'w')
>>> z = zip(x, y)
>>> z
>>> list(z)
[(1, 'u'), (2, 'v'), (4, 'w')]
You can iterate through the obtained zip object or transform it into a list or tuple.
Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:
>>> x = [(1, 2, 4), ('u', 'v', 'w')]
>>> y = zip(*x)
>>> z = list(y)
>>> z
[(1, 'u'), (2, 'v'), (4, 'w')]
You can remove duplicates from a list, that is obtained unique values by converting it to a set if the order of elements is not important:
>>> x = [1, 2, 1, 4, 8]
>>> y = set(x)
>>> y
{8, 1, 2, 4}
>>> z = list(y)
>>> z
[8, 1, 2, 4]
Sequences are sorted by their first elements by default:
>>> x = (1, 'v')
>>> y = (4, 'u')
>>> z = (2, 'w')
>>> sorted([x, y, z])
[(1, 'v'), (2, 'w'), (4, 'u')]
However, if you want to sort them according to their second (or other) elements, you can use the parameter key and an appropriate lambda function as the corresponding argument:
>>> sorted([x, y, z], key=lambda item: item[1])
[(4, 'u'), (1, 'v'), (2, 'w')]
It’s similar if you want to obtain the reversed order:
>>> sorted([x, y, z], key=lambda item: item[1], reverse=True)
[(2, 'w'), (1, 'v'), (4, 'u')]
You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method:
>>> x = {'u': 4, 'w': 2, 'v': 1}
>>> sorted(x.items())
[('u', 4), ('v', 1), ('w', 2)]
They are sorted according to the keys. If you want to them to be sorted according to their values, you should specify the arguments that correspond to key and eventually reverse:
>>> sorted(x.items(), key=lambda item: item[1])
[('v', 1), ('w', 2), ('u', 4)]
>>> sorted(x.items(), key=lambda item: item[1], reverse=True)
[('u', 4), ('w', 2), ('v', 1)]
PEP 498 and Python 3.6 introduced so-called formatted strings or f-strings. You can embed expressions inside such strings. It’s possible and straightforward to treat a string as both raw and formatted. You need to include both prefixes: fr.
>>> fr'u \ n v w={2 + 8}'
'u \\ n v w=10'
Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 5, 20, 1, 12, 31, 230217)
Python doesn’t provide a routine to directly get the index of the maximal or minimal element in a list or tuple. Fortunately, there are (at least) two elegant ways to do so:
>>> x = [2, 1, 4, 16, 8]
>>> max((item, i) for i, item in enumerate(x))[1]
3
If there are two or more elements with the maximal value, this approach returns the index of the last one:
>>> y = [2, 1, 4, 8, 8]
>>> max((item, i) for i, item in enumerate(y))[1]
4
To get the index of the first occurrence, you need to change the previous statement slightly:
>>> -max((item, -i) for i, item in enumerate(y))[1]
3
The alternative way is probably more elegant:
>>> x = [2, 1, 4, 16, 8]
>>> max(range(len(x)), key=lambda i: x[i])
3
>>> y = [2, 1, 4, 8, 8]
>>> max(range(len(y)), key=lambda i: x[i])
3
To find the index of the minimal element, use the function min instead of max.
The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:
>>> import itertools
>>> x, y, z = (2, 8), ['u', 'v', 'w'], {True, False}
>>> list(itertools.product(x, y, z))
[(2, 'u', False), (2, 'u', True), (2, 'v', False), (2, 'v', True),
(2, 'w', False), (2, 'w', True), (8, 'u', False), (8, 'u', True),
(8, 'v', False), (8, 'v', True), (8, 'w', False), (8, 'w', True)]
PEP 465 and Python 3.5 introduced the dedicated infix operator for matrix multiplication @. You can implement it for your class with the methods matmul, rmatmul, and imatmul. This is how elegant the code for multiplying vectors or matrices looks like:
>>> import numpy as np
>>> x, y = np.array([1, 3, 5]), np.array([2, 4, 6])
>>> z = x @ y
>>> z
44
You’ve seen 20 Python tips and tricks that make it interesting and elegant. There are many other language features worth exploring.
#python #web-development #machine-learning
1599831615
Your article is too good and informative. I am searching for same blog and I get the exact article I am thankful to you for sharing this educational article. and the way you wrote is also good, you covered up all the points which I searching for & I am impressed by reading this article. Keep writing and sharing educational article like this which can help us to grow our knowledge.
python classes in pune
software testing course in pune
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1602666000
Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.
In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.
Heres a solution
Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.
But How do we do it?
If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?
The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.
There’s a variety of hashing algorithms out there such as
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips
1597751700
Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…
You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).
Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.
class AnyClass:
def __init__():
print("Init called on its own")
obj = AnyClass()
The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.
The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.
Init called on its own
Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,
class AnyClass:
def __init__(self, var):
self.some_var = var
def __add__(self, other_obj):
print("Calling the add method")
return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2
#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python
1603018800
The** OS module** is a python module that provides the interface for interacting with the underlying operating system that Python is running.
This module provides a portable way of using **operating system **dependent functionality.
OS module comes by default on Python’s standard utility modules therefore you don’t need to install anything to start using it
OS module provides a ton of** methods** of which you use in variety of situation in **interacting **with the operating system ranging from_ creating new file & folder_s to renaming and _deleting t_hem.
You can view all of them by using dir() as shown below
>>>import os
>>>dir(os)
'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names',
'cpu_count', 'ctermid', 'curdir', 'defpath', 'device_encoding',
'posix_fallocate', 'pread', 'putenv', 'pwrite', 'read', 'readlink',
'readv', 'remove', 'removedirs', 'removexattr', 'rename', 'renames'
............................and so on...........................
On this tutorial We will just check some of methods on OS Module
This OS method is used to get the path of the current working directory.
>>>import os
>>>os.getcwd() #getting path of current directory
'/home/kalebu'
#python #python-programming #python-tutorials #learn-python #python-tips #python-developers #python3