<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>scripts Archives - Tech Chronicles</title>
	<atom:link href="http://kostacipo.stream/tag/scripts/feed/" rel="self" type="application/rss+xml" />
	<link>http://kostacipo.stream/tag/scripts/</link>
	<description>Ramblings of a Tech Dude</description>
	<lastBuildDate>Tue, 03 Dec 2019 10:18:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.2</generator>

<image>
	<url>https://kostacipo.stream/wp-content/uploads/2019/12/cropped-profile-32x32.jpg</url>
	<title>scripts Archives - Tech Chronicles</title>
	<link>http://kostacipo.stream/tag/scripts/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>10 Python Tips and Tricks You Should Learn Today</title>
		<link>http://kostacipo.stream/10-python-tips-and-tricks-you-should-learn-today/</link>
					<comments>http://kostacipo.stream/10-python-tips-and-tricks-you-should-learn-today/#respond</comments>
		
		<dc:creator><![CDATA[Majordomo]]></dc:creator>
		<pubDate>Tue, 03 Dec 2019 10:13:56 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scripts]]></category>
		<guid isPermaLink="false">http://www.kostacipo.stream/?p=1413</guid>

					<description><![CDATA[<p>&#160; Python snippets that can be taken as a reference for your daily work According to Stack Overflow, Python is the fastest growing programming language. The latest report from Forbes states that Python showed a 456-percent growth in last year. Netflix uses Python, IBM uses Python, and hundreds of other companies all use Python. Let’s [&#8230;]</p>
<p>The post <a href="http://kostacipo.stream/10-python-tips-and-tricks-you-should-learn-today/">10 Python Tips and Tricks You Should Learn Today</a> appeared first on <a href="http://kostacipo.stream">Tech Chronicles</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>&nbsp;</p>
<blockquote>
<p class="aq ef gc gd av"><em><span style="font-size: 10pt;">Python snippets that can be taken as a reference for your daily work</span></em></p>
</blockquote>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<p id="9c0b" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">According to Stack Overflow, Python is the fastest growing programming language. The latest <a class="bo dd im in io ip" href="https://www.whatech.com/development/press-release/442278-why-developers-vote-python-as-the-best-application-programming-language" target="_blank" rel="noopener nofollow noreferrer">report from Forbes</a> states that Python showed a 456-percent growth in last year. Netflix uses Python, IBM uses Python, and hundreds of other companies all use Python. Let’s not forget Dropbox. Dropbox is also created in Python. According to <a class="bo dd im in io ip" href="https://insights.dice.com/2016/02/01/whats-hot-and-not-in-tech-skills/" target="_blank" rel="noopener nofollow noreferrer">research by Dice</a> Python is also one of the hottest skills to have and also the most popular programming language in the world based on the <a class="bo dd im in io ip" href="https://pypl.github.io/PYPL.html" target="_blank" rel="noopener nofollow noreferrer">Popularity of Programming Language Index</a>.</p>
<p id="8af1" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph=""><strong>Some of the advantages Python</strong> offers when compared to other programming languages are:</p>
<ol>
<li>&#8211; Compatible with major platforms and operating systems</li>
<li>&#8211; Many open-source frameworks and tools</li>
<li>&#8211; Readable and maintainable code</li>
<li>&#8211; Robust standard library</li>
<li>&#8211; Standard test-driven development</li>
</ol>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4>&nbsp;</h4>
<h4 id="f9d1" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">Python Tips and Tricks</h4>
<p id="f321" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">In this piece, We’ll present 10 useful code tips and tricks that can help you in your day-to-day tasks. So without further ado, let’s get started.</p>
<h4 id="5217" class="ju jv cn ar aq jw jx kn jz ko kb kp kd kq kf kr kh">1. Concatenating Strings</h4>
<p id="2b3d" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">When you need to concatenate a list of strings, you can do this using a <em class="ks">for loop</em> by adding each element one by one. However, this would be very inefficient, especially if the list is long. In Python, strings are immutable, and thus the left and right strings would have to be copied into the new string for every pair of concatenation.</p>
<p id="24ac" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">A better approach is to use the <code class="ib kt ku kv kw b">join()</code> function as shown below:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="3d16" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">characters = ['p', 'y', 't', 'h', 'o', 'n']
word = "".join(characters)
print(word) <strong class="kw ld"># python</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="1162" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">2. Using List Comprehensions</h4>
<p id="47e1" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">List comprehensions are used for creating new lists from other iterables. As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. List comprehension is faster because it is optimized for the Python interpreter to spot a predictable pattern during looping.</p>
<p id="a7bc" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">As an example let’s find the squares of the first five whole numbers using list comprehensions.</p>
<pre class="ho hp hq hr hs kx ky du"><span id="63bb" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">m = [x ** 2 for x in range(5)]
print(m)<strong class="kw ld"> # [0, 1, 4, 9, 16]</strong></span></pre>
<p id="61c0" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Now let’s find the common numbers from two list using list comprehension</p>
<pre class="ho hp hq hr hs kx ky du"><span id="12d9" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num) <strong class="kw ld"># [2, 3, 4]</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="a568" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">3. Iterate With <code class="ib kt ku kv kw b">enumerate()</code></h4>
<p id="4452" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object.</p>
<p id="79dd" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Let’s solve the classic coding interview question named popularly as the Fizz Buzz problem.</p>
<blockquote class="le lf lg">
<p id="9622" class="iq ir cn ks is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph=""><span style="font-size: 14pt;">Write a program that prints the numbers in a list, for multiples of ‘3’ print “fizz” instead of the number, for the multiples of ‘5’ print “buzz” and for multiples of both 3 and 5 it prints “fizzbuzz”.</span></p>
</blockquote>
<pre class="ho hp hq hr hs kx ky du"><span id="e165" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">numbers = [30, 42, 28, 50, 15]
for i, num in enumerate(numbers):
    if num % 3 == 0 and num % 5 == 0:
       numbers[i] = 'fizzbuzz'
    elif num % 3 == 0:
       numbers[i] = 'fizz'
    elif num % 5 == 0:
       numbers[i] = 'buzz'
print(numbers) <strong class="kw ld"># ['fizzbuzz', 'fizz', 28, 'buzz', 'fizzbuzz']</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="a416" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">4. Using ZIP When Working with Lists</h4>
<p id="5b40" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Suppose you were given a task to combine several lists with the same length and print out the result? Again, here is a more generic way to get the desired result by utilizing <code class="ib kt ku kv kw b">zip()</code>as shown in the code below:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="1c92" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">countries = ['France', 'Germany', 'Canada']
capitals = ['Paris', 'Berlin', 'Ottawa']
for country, capital in zip(countries,capitals):
    print(country, capital) <strong class="kw ld"># France Paris 
                              Germany Berlin
                              Canada Ottawa</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="9589" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">5. Using itertools</h4>
<p id="7ffc" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">The Python <code class="ib kt ku kv kw b">itertools</code> module is a collection of tools for handling iterators. <code class="ib kt ku kv kw b">itertools</code> has multiple tools for generating iterable sequences of input data. Here I will be using <code class="ib kt ku kv kw b">itertools.combinations()</code> as an example. <code class="ib kt ku kv kw b">itertools.combinations()</code> is used for building combinations. These are also the possible groupings of the input values.</p>
<p id="8042" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Let’s take a real world example to make the above point clear.</p>
<blockquote class="le lf lg">
<p id="6d38" class="iq ir cn ks is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph=""><span style="font-size: 14pt;">Suppose there are four teams playing in a tournament. In the league stages every team plays against every other team. Your task is to generate all the possible teams that would compete against each other.</span></p>
</blockquote>
<p id="46d5" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Let’s take a look at the code below:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="1a10" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">import itertools
friends = ['Team 1', 'Team 2', 'Team 3', 'Team 4']
list(itertools.combinations(friends, r=2)) <strong class="kw ld"># [('Team 1', 'Team 2'),      ('Team 1', 'Team 3'),  ('Team 1', 'Team 4'),  ('Team 2', 'Team 3'),  ('Team 2', 'Team 4'),  ('Team 3', 'Team 4')]</strong></span></pre>
<p id="c9e8" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">The important thing to notice is that order of the values doesn’t matter. Because <code class="ib kt ku kv kw b">('Team 1', 'Team 2')</code> and <code class="ib kt ku kv kw b">('Team 2', 'Team 1')</code> represent the same pair, only one of them would be included in the output list. Similarly we can use <code class="ib kt ku kv kw b">itertools.permutations()</code> as well as other functions from the module. For a more complete reference, check out <a class="bo dd im in io ip" href="https://medium.com/@jasonrigden/a-guide-to-python-itertools-82e5a306cdf8" target="_blank" rel="noopener noreferrer">this amazing tutorial</a>.</p>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="8668" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">6. Using Python Collections</h4>
<p id="30f1" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Python collections are container data types, namely lists, sets, tuples, dictionary. The collections module provides high-performance datatypes that can enhance your code, making things much cleaner and easier. There are a lot of functions provided by the collections module. For this demonstration, I will be using <code class="ib kt ku kv kw b">Counter()</code> function.</p>
<p id="f158" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">The <code class="ib kt ku kv kw b">Counter()</code> function takes an iterable, such as a list or tuple, and returns a Counter Dictionary. The dictionary’s keys will be the unique elements present in the iterable, and the values for each key will be the count of the elements present in the iterable.</p>
<p id="3be5" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">To create a <code class="ib kt ku kv kw b">counter</code> object, pass an iterable (list) to <code class="ib kt ku kv kw b">Counter()</code> function as shown in the code below.</p>
<pre class="ho hp hq hr hs kx ky du"><span id="fd71" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">from collections import Countercount = Counter(['a','b','c','d','b','c','d','b'])
print(count) <strong class="kw ld"># Counter({'b': 3, 'c': 2, 'd': 2, 'a': 1})</strong></span></pre>
<p id="abcb" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">For a more complete reference, check out my <a class="bo dd im in io ip" href="https://towardsdatascience.com/a-hands-on-guide-to-python-collections-aa350cb399e3" target="_blank" rel="noopener noreferrer">python collections tutorial</a>.</p>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="59f2" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">7. Convert Two Lists Into a Dictionary</h4>
<p id="8051" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Let’s say we have two lists, one list contains names of the students and second contains marks scored by them. Let’s see how we can convert those two lists into a single dictionary. Using the zip function, this can be done using the code below:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="f095" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">students = ["Peter", "Julia", "Alex"]
marks = [84, 65, 77]
dictionary = dict(zip(students, marks))
print(dictionary) <strong class="kw ld"># {'Peter': 84, 'Julia': 65, 'Alex': 77}</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="9eae" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">8. Using Python Generators</h4>
<p id="b00e" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Generator functions allow you to declare a function that behaves like an iterator. They allow programmers to make an iterator in a fast, easy, and clean way. Let’s take an example to explain this concept.</p>
<blockquote class="le lf lg">
<p id="5f94" class="iq ir cn ks is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph=""><span style="font-size: 14pt;">Suppose you’ve been given to find the sum of the first 100000000 perfect squares, starting with 1.</span></p>
</blockquote>
<p id="6167" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Looks easy right? This can easily be done using list comprehension but the problem is the large inputs size. As an example let’s take a look at the below code:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="07c6" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">t1 = time.clock()
sum([i * i for i in range(1, 100000000)])
t2 = time.clock()
time_diff = t2 - t1
print(f"It took {time_diff} Secs to execute this method") <strong class="kw ld"># It took 13.197494000000006 Secs to execute this method</strong></span></pre>
<p id="1710" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">On increasing the perfect numbers we need to sum over, we realize that this method is not feasible due to higher computation time. Here’s where Python Generators come to the rescue. On replacing the brackets with parentheses we change the list comprehension into a generator expression. Now let’s calculate the time taken:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="0f8e" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">t1 = time.clock()
sum((i * i for i in range(1, 100000000)))
t2 = time.clock()
time_diff = t2 - t1
print(f"It took {time_diff} Secs to execute this method") <strong class="kw ld"># It took 9.53867000000001 Secs to execute this method</strong></span></pre>
<p id="e1e3" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">As we can see, time taken has been reduced quite a bit. This effect will be even more pronounced for larger inputs.</p>
<p id="eea1" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">For a more complete reference, check out my article <a class="bo dd im in io ip" href="https://towardsdatascience.com/reduce-memory-usage-and-make-your-python-code-faster-using-generators-bd79dbfeb4c" target="_blank" rel="noopener noreferrer">Reduce Memory Usage and Make Your Python Code Faster Using Generators</a>.</p>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="9d52" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">9. Return Multiple Values From a Function</h4>
<p id="bf2d" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Python has the ability to return multiple values from a function call, something missing from many other popular programming languages. In this case the return values should be a comma-separated list of values and Python then constructs a <em class="ks">tuple</em> and returns this to the caller. As an example see the code below:</p>
<pre class="ho hp hq hr hs kx ky du"><span id="8a66" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">def multiplication_division(num1, num2):
    return num1*num2, num1/num2</span><span id="6f8e" class="kz jv cn ar kw b bj lh li lj lk ll lb r lc" data-selectable-paragraph="">product, division = multiplication_division(15, 3)
print("Product=", product, "Quotient =", division) <strong class="kw ld"># Product= 45 Quotient = 5.0</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="6f25" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">10. Using sorted() Function</h4>
<p id="6519" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">Sorting any sequence is very easy in Python using the built-in method <code class="ib kt ku kv kw b">sorted()</code>which does all the hard work for you. <code class="ib kt ku kv kw b">sorted()</code>sorts any sequence (list, tuple) and always returns a list with the elements in sorted manner. Let’s take an example to sort a list of numbers in ascending order.</p>
<pre class="ho hp hq hr hs kx ky du"><span id="13a7" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">sorted([3,5,2,1,4]) <strong class="kw ld"># [1, 2, 3, 4, 5]</strong></span></pre>
<p id="55a9" class="iq ir cn ar is b it iu iv iw ix iy iz ja jb jc jd" data-selectable-paragraph="">Taking another example, let’s sort a list of strings in descending order.</p>
<pre class="ho hp hq hr hs kx ky du"><span id="cbf4" class="kz jv cn ar kw b bj la lb r lc" data-selectable-paragraph="">sorted(['france', 'germany', 'canada', 'india', 'china'], reverse=True) <strong class="kw ld"># ['india', 'germany', 'france', 'china', 'canada']</strong></span></pre>
</div>
</div>
</section>
<section class="fd fe ff fg fh">
<div class="n p">
<div class="ac ae af ag ah fi aj ak">
<h4 id="c1ec" class="ju jv cn ar aq jw jx jy jz ka kb kc kd ke kf kg kh">Conclusions</h4>
<p id="9d84" class="iq ir cn ar is b it ki iv kj ix kk iz kl jb km jd" data-selectable-paragraph="">In this article, We&#8217;ve presented 10 Python tips and tricks that can be used as a reference in your day-to-day work. We hope you enjoyed this article.</p>
</div>
</div>
</section>
<p>&nbsp;</p>
<p>The post <a href="http://kostacipo.stream/10-python-tips-and-tricks-you-should-learn-today/">10 Python Tips and Tricks You Should Learn Today</a> appeared first on <a href="http://kostacipo.stream">Tech Chronicles</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://kostacipo.stream/10-python-tips-and-tricks-you-should-learn-today/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
