SoFunction
Updated on 2024-11-16

Essential Python Utilities and Tools for Beginners

I. Exchange of variables

x = 6
y = 5
x, y = y, x
print x
>>> 5
print y
>>> 6

II. If Statements on the Line

print "Hello" if True else "World"
>>> Hello

III. Connections

The last way below looks COOL when binding two objects of different types.

nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
print nfc + afc
>>> ['Packers', '49ers', 'Ravens', 'Patriots']
print str(1) + " world"
>>> 1 world
print `1` + " world"
>>> 1 world
print 1, "world"
>>> 1 world
print nfc, 1
>>> ['Packers', '49ers'] 1

IV. Number skills

# Divide and round down
print 5.0//2
>>> 2
# 2 to the 5th power
print 2**5
>> 32

V. Note the division of floating-point numbers

print .3/.1
>>> 2.9999999999999996
print .3//.1
>>> 2.0

VI. Comparison of values

It's a great simplicity that I've rarely seen in many languages.

x = 2
if 3 > x > 1:
   print x
>>> 2
if 1 < x > 0:
   print x
>>> 2

VII. Iterating two lists simultaneously

nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
     print teama + " vs. " + teamb

>>> Packers vs. Ravens
>>> 49ers vs. Patriots

VIII. List iteration with indexing

teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
    print index, team
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots

IX. List of derivatives

A list is known and we can swipe out the even list method:

numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
    if number%2 == 0:
        (number)

The transformation is as follows:

numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]

Isn't that awesome, haha.

X. Dictionary Derivation

Similar to list derivation, dictionaries can do the same job:

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}

XI. Initializing list values

items = [0]*3
print items
>>> [0,0,0]

XII. Conversion of lists to strings

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
>>> 'Packers, 49ers, Ravens, Patriots'

XIII. Getting elements from a dictionary

I'll admit that the try/except code isn't elegant, but here's an easy way to try to look up the key in the dictionary, and if it doesn't find the corresponding alue will be set to its variable value with the second argument.

data = {'user': 1, 'name': 'Max', 'three': 4}
try:
   is_admin = data['admin']
except KeyError:
   is_admin = False
data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = ('admin', False)

XIV. Getting a subset of a list

Sometimes you only need some of the elements in a list, here are some ways to get a subset of the list.

x = [1,2,3,4,5,6]
# The first 3
print x[:3]
>>> [1,2,3]
# Four in the middle
print x[1:5]
>>> [2,3,4,5]
#The last three
print x[-3:]
>>> [4,5,6]
# Odd terms
print x[::2]
>>> [1,3,5]
# even terms
print x[1::2]
>>> [2,4,6]

XV. Gathering

In addition to python's built-in data types, the collection module also includes special use cases where Counter is useful. If you've participated in the Facebook HackerCup this year, you may even find it useful.

from collections import Counter
print Counter("hello")
>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

XVI. Iterative tools

Like the collections library, there is another library called itertools that is really efficient for certain problems. One of the use cases is finding all combinations, which tells you all the ways that elements in a group can't be combined

from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
    print game
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')

XVII. False == True

More than practical techniques this is an interesting thing, in python True and False are global variables, so:

False = True
if False:
   print "Hello"
else:
   print "World"
>>> Hello

To this article on the newbie must have Python utility tips and tools to this article, more related Python utility tips and tools, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!