Convenient Python methods, etc.

Introduction

Python is widespread and has many developers. I think the best feature is simplicity. For example, you can output hello world in just one line. It's hard to do in other languages.

image.png

Source: https://www.benfrederickson.com/ranking-programming-languages-by-github-users/

Output hello world

print("hello world!")

Convenience of calculation

print(2 * 3)  //multiplication
print(2 ** 3) //Exponentiation

print(22 / 7) //There are decimals
print(22 // 7) //integer

6 8 3.142857142857143 3

Variable value exchange

Like the Go language, it can be exchanged directly without the need for temp variables.

a = 10
b = 20
a, b = b, a
print(a)
print(b)

Example of finding the Fibonacci sequence:

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

fib(900)

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Join method that can be joined by characters

color = ["red", "green", "blue"]
print(" ".join(color))

red green blue

You can easily concatenate array data with a specified character string. LOOP is also unnecessary and convenient.

Inversion of string

k8s = "kubernates"
print(k8s[::-1])

setanrebuk

You don't even have to call a method.

Array reversal

It will be used more often for array inversion than for string inversion.

alphas = ["a", "b", "c", "d"]
print(alphas[::-1])

['d', 'c', 'b', 'a']

It is written in the same way as in the case of character string inversion.

Eliminating duplicate values in an array

numbers = [4, 3, 2, 1, 1, 2, 3, 4]
print(list(set(numbers)))

[1, 2, 3, 4]

Range comparison

In JAVA, if you want to judge 6 years old or older and 18 years old or younger, you need two formulas like ʻif (6 <= age && age <= 18) {}`. The range cannot be judged. With Python, you can.

age = 10
if (6 <= age <= 18) :
    print("I am a student.")

I'm a student.

It's convenient because you can understand the logic at a glance.

for else You might think that else is used with if, but in Python you can also use it with for.

for i in range(5):
    print(i)
else:
    print("LOOP completed")

0 1 2 3 4 LOOP completed

It may seem a little strange, it's a syntax unique to Python. This alone doesn't seem to have much use, but it's useful when used with break. If the loop is stopped by break, the else process will not be executed.

for i in range(5):
    if i > 3:
        break
    
    print(i)
else:
    print("LOOP completed")

0 1 2 3

Default value can be set by get in the dictionary

user = {"lastName": "Tanaka"}
print(user.get("firstName", "〇〇"))

〇〇

In such a case, it is convenient because it is not necessary to determine whether or not it exists after acquiring the value.

Sort by dictionary key

The process of sorting by dictionary keys is also common.

user = {"userName": "Tanaka", 
    "address3": "3",  
    "address2": "2", 
    "address1": "1" }
print(user)

print(sorted(user.items(), key = lambda x: x[1]))

{'userName':'Tanaka','address3': '3','address2': '2','address1': '1'} [('address1', '1'), ('address2', '2'), ('address3', '3'), ('userName','Tanaka')]

An array sorted by dictionary key is generated using the sorted method. There are many situations where this is used.

enumerate function

fruits = ['banana', 'Apple', 'Mandarin orange']
print(list(enumerate(fruits)))

[(0,'banana'), (1,'apple'), (2,'mandarin orange')] You can number it.

I have summarized several types of operations easily.

There are many other useful methods and modules in Python.

https://www.python.org/

that's all

Recommended Posts

Convenient Python methods, etc.
[python] class basic methods
String object methods in Python
[python] super (), inheritance, __init__, etc.
Twitter posts on Python 3 etc.
Dynamically call methods in Python
Does python inherit special methods?
Python
Samples of Python getters, setters, etc.
[Python Queue] Convenient use of Deque
Dynamically define functions (methods) in Python
Python classes and instances, instance methods
[Introduction to Udemy Python3 + Application] 18. List methods
Statistical basics and Python, graphing, etc. (memo)
Implement __eq__ etc. generically in Python class
Bind methods to Python classes and instances
Python memo using perl --format is convenient.
[Python] REST API essential, convenient library summary
Japan's simplest Python memo (dialog box, etc.)
Private methods and fields in python [encryption]
Python 3 multi-process Pool methods should use imap_unordered
Summary of built-in methods in Python list
Python exception handling a little more convenient