50 + Python 3 Tips & Tricks

6/29/2020

50+ Python 3 Tips & Tricks - Towards AI--Multidisciplinary Science Journal - Medium

To make Medium work, we log user data. By using Medium, you agree to our Privacy Policy, including cookie policy.

PROGRAMMING, PYTHON

50+ Python 3 Tips & Tricks

These Python Gems Will Make Your Code Beautiful and Elegant

Eyal Trabelsi Jul 18, 2019 ? 4 min read

Here is a list of python tips and tricks to help you write an elegant Python 3 code! This article is divided into different kinds of tricks:

Python iterable tricks. Python comprehension tricks. Python unpacking tricks. Python itertools tricks.



1/18

6/29/2020

50+ Python 3 Tips & Tricks - Towards AI--Multidisciplinary Science Journal - Medium

To maPkyetMheodniucmolwleocrtki,ownes ltorgicuksse.r data. By using Medium, you agree to our Privacy Policy, including

cookie policy.

Python other tricks.

Python easter eggs.

Python tricks to understand the context.

Python Iterables tricks

Creating a sequence of numbers (zero to ten with skips).

1 >>> range(0,10,2) 2 [0, 2, 4, 6, 8] 3

python-tricks_iterables_1.py hosted with by GitHub

view raw

Summing a sequence of numbers (calculating the sum of zero to ten with skips).

1 >>> l = range(0,10,2) 2 >>> sum(l) 3 20

python-tricks_iterables_2.py hosted with by GitHub

view raw

Checking whether any element in the sequence is Truthful (checking whether any elements between zero and ten with skips are even).

1 >>> any(a % 2==0 for a in range(0,10,2)) 2 True

python-tricks_iterables_3.py hosted with by GitHub

view raw

Checking whether all elements in the sequence are Truthful (checking whether all elements between zero and ten with skips are even).

1 2 >>> all(a % 2==0 for a in range(0,10,2)) 3 True

python-tricks_iterables_4.py hosted with by GitHub

view raw



2/18

6/29/2020

50+ Python 3 Tips & Tricks - Towards AI--Multidisciplinary Science Journal - Medium

TCoummakuelaMteivdeiusmuwmomrki,nwgealosgeuqsueerndcaetao. Bf ynuusminbgeMresd(icuamlc, yuoluataignrgeethtoeocuurmPruivlaactyivPeolsicuym, inoclfuzdeinrgo to ten cwooitkhiespkoilpicsy). .

1 >>> import numpy as np 2 >>> res = list(np.cumsum(range(0,10,2))) 3 >>> res 4 [ 0, 2, 6, 12, 20]

python-tricks_iterables_5.py hosted with by GitHub

view raw

Given each iterable we construct a tuple by adding an index.

1 >>> a = ['Hello', 'world', '!'] 2 >>> list(enumerate(a)) 3 [(0, 'Hello'), (1, 'world'), (2, '!')]

python-tricks_iterables_3.py hosted with by GitHub

view raw

Concatenating iterable to a single string.

1 >>> a = ["python","really", "rocks"] 2 >>> " ".join(a) 3 'python really rocks'

python-tricks_iterables_5.py hosted with by GitHub

view raw

Combining two iterable of tuples or pivot nested iterables.

1 # Combining two iterables 2 >>> a = [1, 2, 3] 3 >>> b = ['a', 'b', 'c'] 4 >>> z = zip(a, b) 5 >>> z 6 [(1, 'a'), (2, 'b'), (3, 'c')] 7 8 # Pivoting list of tuples 9 >>> zip(*z) 10 [(1, 2, 3), ('a', 'b', 'c')]

python-tricks_comprehension_6.py hosted with by GitHub

Getting min/max from iterable (with/without specific function).

view raw

1 # Getting maximum from iterable



3/18

6/29/2020

50+ Python 3 Tips & Tricks - Towards AI--Multidisciplinary Science Journal - Medium

To m2ake>M>>edaiu=m[1w,o2rk,, -w3e] log user data. By using Medium, you agree to our Privacy Policy, including cook3ie p>o>l>icym.ax(a)

42 5 6 # Getting maximum from iterable 7 >>> min(a) 81 9 10 # Bot min/max has key value to allow to get maximum by appliing function 11 >>> max(a,key=abs) 12 3

python-tricks_iterables_7.py hosted with by GitHub

view raw

Getting sorted iterable (can sort by "compare" function).

1 >>> a = [1, 2, -3] 2 >>> sorted(a) 3 [-3, 1, 2] 4 5 >>> sorted(a,key=abs) 6 [1, 2, -3]

python-tricks_iterables_8.py hosted with by GitHub

view raw

Splitting a single string to list.

1 >>> s = "a,b,c" 2 >>> s.split(",") 3 ["a", "b", "c"]

python-tricks_iterables_9.py hosted with by GitHub

view raw

Initializing a list filled with some repetitive number.

1 >> [1]* 10 2 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

python-tricks_iterables_10.py hosted with by GitHub

view raw

Merging/Upserting two dictionaries.

1 >>> a = {"a":1, "b":1}

2 >>> b = {"b":2, "c":1}

3 >>> a.update(b)



4/18

6/29/2020

50+ Python 3 Tips & Tricks - Towards AI--Multidisciplinary Science Journal - Medium

To4mak>e>M> eadium work, we log user data. By using Medium, you agree to our Privacy Policy, including coo5kie {p"oal"ic:y1., "b":2, "c":1}

python-tricks_iterables_11.py hosted with by GitHub

view raw

Naming and saving slices of iterables.

1 2 # Naming slices (slice(start, end, step)) 3 >>> a = [0, 1, 2, 3, 4, 5] 4 >>> LASTTHREE = slice(-3, None) 5 >>> LASTTHREE 6 slice(-3, None, None) 7 >>> a[LASTTHREE] 8 [3, 4, 5]

python-tricks_iterables_13.py hosted with by GitHub

view raw

Finding the index of an item in a list.

1 >>> a = ["foo", "bar", "baz"] 2 >>> a.index("bar") 31

python-tricks_iterables_14.py hosted with by GitHub

view raw

Finding the index of the min/max item in an iterable.

1 >>> a = [2, 3, 1] 2 >>> min(enumerate(a),key=lambda x: x[1])[0] 32

python-tricks_iterables_15.py hosted with by GitHub

view raw

Rotating iterable by k elements.

1 >>> a = [1, 2, 3, 4] 2 >>> k = 2 3 >>> a[-2:] + a[:-2] 4 [3, 4, 1, 2]

python-tricks_iterables_16.py hosted with by GitHub

view raw

Removing useless characters on the end/start/both of your string.



5/18

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download