Skip to main content

Python cheatsheet for beginner


View on Github

Recommended

Writing shorthand statements in python

Python is having shorthand statements and shorthand operators. These things will help you write more logic with less number of statements.
We will see those available shorthand statements.

lambda statement

Probably every body is aware of the lambda functions. The statement lambda is helpful to write single line functions with out naming a function. This will return the function reference where you can assign it to any arbitrary variable. It's more like JavaScript anonymous functions.
foo = lambda a: a+3
foo(3)
6
foo(8)
11

SELF CALLED LAMBDA

You can write the lambda and you can make it call it self like self-invoking functions in javascript. Let's see an example.
(lambda a: a+3)(8)
11
(lambda x: x**x)(3)
27

List Comprehension

List Comprehension is the great feature that python is having. Using this feature you can reduce the lot of code, you can reduces space complexity of the code. Simple for loops can be written using list comprehension.
Syntax:
L = [ mapping-expression for element in source-list if filter-expression ]
Where:
L Variable, result gets assigned to
mapping-expression Expression, which is executed on every loop if only filter-expression > in if condition resolved as True
This list comprehension is equivalent to.
result = []
for element in source-list:
  if filter-expression:
    result.append(mapping-expression)

EXAMPLE

Lets see list comprehension example. Get even number from the given range.
  • Usual code
result = []
for i in range(10):
  if i%2 == 0:
    result.append(i)

print(result)
[0, 2, 4, 6, 8]
  • List Comprehension
[i for i in range(10) if i%2==0]
[0, 2, 4, 6, 8]

Dict Comprehension

Dict comprehension is available in python 2.7 and 3.x. This syntax will provide you the way to encapsulate several lines you use to create dictionaries into one line. It's is similar to list comprehension but we use dict literals {} instead of [].
Syntax:
{key:value for element in source-list if filter-expression }
Let's how we use it by an example.
I have a list of fruits, I want to make it dictionary by changing their case
['APPLE', 'MANGO', 'ORANGE']
I want to convert all keys into lower case. This is we would do with out using comprehension.
l = ['MANGO', 'APPLE', 'ORANGE']

d = {}

for i in l:
  d[i.upper()] = 1

{'ORANGE': 1, 'MANGO': 1, 'APPLE': 1}
Using Simple list comprehension.
{i.upper(): 1 for i in l}

Set Comprehension

Set comprehension syntax is very much similar to dict comprehension with a small difference.
Let’s consider dict comprehension example. Using following statement you generate set
{i.upper() for i in l}
Where we haven’t specified value like we do in dict comprehension

Generator Expression

You might have already know about generators. Any function which contains yield statment is called generator. generator gives iterable where we can call next method to get the next item in the sequence. Python got short notation for this generators like lambda. It is same as list comprehension but we enclose the expression with touple literals instead.
  • GENERATOR FUNCTION
def gen():
  for i in range(10):
    yield i 
g = gen()
<generator object gen at 0x7f60fa104410>
g.next()
0
g.next()
1
  • GENERATOR EXPRESSION
Same generator function can written as follow.
g = (i for i in range(10))
g
<generator object <genexpr> at 0x7f60fa1045f0>
g.next()
0

Shorthand If Else

Like C and javascript ternary operator (?:) you can write short hand if-else comparison. By taking readability into account we have following syntax in python
if-expression if (condition) else else-expression
This is equivalent to.
if True:
  print("This is True")
else:
  print("This is False")

Tuple Unpacking

Python 3 even more powerful unpacking feature. Here it is.
Example:
a, rest = [1, 3, 4, 6]
In this case, a will get 1 and rest of the list will get assigned to variable rest. i.e [3, 4, 6]

String Concatenation with delimiter

If you want to concatenate list of strings with some random delimiter. You can do that by using string method join
" || ".join(["hello", "world", "how", "are", "you"])

'hello || world || how || are || you'

Powerful One-Liners

Are you tired of reading through lines of code and getting lost in conditional statements? Python one-liners might just be what you are looking for. For example, the conditional statements.
if alpha > 7:
   beta = 999
elif alpha == 7:
   beta = 99
else:
   beta = 0
can really be simplified to:
beta = 999 if alpha > 7 else 99 if alpha == 7 else 0

Removing duplicates items from a list

Most of the time we wanted to remove or find the duplicate item from the list. Let see how to delete duplicate from a list. The best approach is to convert a list into a set. Sets are unordered data-structure of unique values and don’t allow copies.
listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
print("Original= ", listNumbers)

listNumbers = list(set(listNumbers))
print("After removing duplicate= ", listNumbers)

How to efficiently compare two unordered lists

Above two lists contains the same element only their order is different. Let see how we can find two lists are identical.
  • We can use collections.Counter method if our object is hashable.
  • We can use sorted() if objects are orderable.
from collections import Counter

one = [33, 22, 11, 44, 55]
two = [22, 11, 44, 55, 33]
print("is two list are b equal", Counter(one) == Counter(two))

Convert Byte to String

To convert byte to string we can decode the bytes object to produce a string. You can decode in the charset you want.
byteVar = b"pynative"
str = str(byteVar.decode("utf-8"))
print("Byte to string is" , str )

Convert hex string, String to int

hexNumber = "0xfde"
stringNumber="34"

print("Hext toint", int(hexNumber, 0))
print("String to int", int(stringNumber, 0))

Comments

Popular posts from this blog

Cách mã hóa mật khẩu trong Kali Linux 2016.2 | Encrypt Passwords

Xin chào tất cả mọi người ! Như tất cả mọi người cũng đã biết việc mã hóa mật khẩu là vô cùng quan trọng trong thời buổi công nghệ thông tin phát triển như vũ bão hiện nay. Việc để mật khẩu một cách bình thường là vô cùng nguy hiểm. Hôm nay tôi xin giới thiệu cho tất cả mọi người một công cụ chuyên mã hóa mật khẩu trên Kali Linux đó chính là HashCode Tool. Việc cài đặt và sử dụng HashCode rất đơn giản, chúng ta sẽ bắt đầu luôn nào ! Bước 1:Download  Để Download HashCode các bạn có thể tải bằng cách: ~# cd Desktop ~# git clone https://github.com/Sup3r-Us3r/HashCode.git Sau đó chờ tải file HashCode về. File sẽ được lưu ở ngoài màn hình Desktop. Bước 2: Cài đặt (Install) Sau khi file đã tải xong các bạn trỏ tới file: ~# cd HashCode Chạy 3 lệnh tiếp theo: ~# sudo chmod +x hashcode-en.py ~# sudo chmod +x hashcode-pt.py ~# sudo chmod +x hashcodegui.py Sau khi chạy xong 3 lệnh trên vậy là việc cài đặt của chúng ta đã hoàn tất và bây giờ chúng ta hãy c...

10 lệnh nguy hiểm nhất của Linux - Không bao giờ nên chạy trên Linux Os

Terminal Linux là một trong những công cụ mạnh mẽ nhất trong thế giới Linux OS. Bạn có thể làm bất cứ điều gì với thiết bị đầu cuối Linux, bất cứ điều gì bạn muốn. Linux những dòng lệnh giúp ta thấy thú vị hơn, hữu ích và năng suất các tính năng. Nhưng nó có thể rất nguy hiểm, đặc biệt là khi bạn không biết bạn đang làm gì. Ngay cả một sai lầm nhỏ cũng có thể dẫn đến mất dữ liệu và hệ điều hành của bạn. Một người sử dụng Linux mới nên rất cẩn thận trong khi thực hiện các lệnh. Chúng tôi chỉ muốn làm cho bạn biết về một số lệnh mà bạn nên suy nghĩ trước khi thực hiện chúng.   Đây là 10 lệnh chết người nhất của Linux mà bạn nên biết trước khi thực hiện chúng. 1. rm -rf Lệnh rm -rf là ​​một trong những cách nhanh nhất để xóa toàn bộ các tệp và thậm chí toàn bộ nội dung. Lệnh này dẫn đến rất nhiều mất mát.      Rm: rm lệnh trong Linux được sử dụng để xóa / xóa các tập tin.      Rm -r: lệnh này sử dụng để xóa thư mục đệ quy và làm trố...

Cách cài đặt ibus-unikey trên Kali Linux 2016.2

Cách cài đặt ibus-unikey trên Kali Linux 2016.2   Lỗi không cái được ibus-unikey là do file sources.list của máy các bạn còn thiếu lên là mình đã để toàn bộ file của sources.list mình để trong mô tả dưới video. Có gì mọi người có thể comment dưới bài viết này hoặc trong video mình sẽ trả lời. Mong các bạn thấy bài viết hữu ích ! Chúc bạn thành công !