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

Hướng dẫn cài đặt Python 3 trên Kali Linux - How to install Python 3 on Kali Linux

Xin chào tất cả mọi người, Python là một ngôn ngữ lập trình có thế nói là vô cùng "báo đạo" trong giới lập trình ngày nay. Với các phiên bản của Kali Linux mặc định sẽ là python 2.x.x. Tuy nhiên để đuổi kịp theo thời đại, thì Python đã nâng cấp lên phiên bản Python  3 cũng khá lâu rồi. Hôm nay mình xin hướng dẫn các bạn cài đặt Python 3 1 cách rất là simple trên Kali Linux. Ở đây mình hướng dẫn cài đặt Python 3.3.2. Bước 1 : Mở Terminal và copy đoạn mã sau: wget http://python.org/ftp/python/3.3.2/Python-3.3.2.tgz && tar -xvf Python-3.3.2.tgz Bước 2: Tiếp tục gõ: 2.a :  cd Python-3.3.2 2.b: ./configure 2.c: make 2.d: sudo make altinstall Sau khi cài đặt xong để có thể sử dụng bạn phải gõ python3 để chạy, còn không mặc định sẽ là phiên bản Python 2 cũ kia. Chỉ với các bước đơn giản như trên là bạn đã cài đặt thành công Python 3 trên Kali Linux. Quá đơn giản phải không nào. Chúc bạn thành công !

Lỗ hổng trên Samba cho phép tin tặc xâm nhập máy tính Linux từ xa

S amba là một phần mềm mã nguồn mở chạy trên các nền tảng HĐH phổ biến như Windows, Linux, IBM hay OpenVMS. Nó cho phép người dùng các hệ điều hành không phải Windows như GNU/Linux hay macOS chia sẻ thư mục, tập tin, máy tin với Windows thông qua giao thức SMB. Lỗ hổng thực thi đoạn mã từ xa (CVE-2017-7497) mới được phát hiện ảnh hưởng tới tất cả các phiên bản mới kể từ Samba 3.5.0 phát hành vào 1/3/2010. Samba viết trên trang của mình vào hôm thứ Tư: " Tất cả các phiên bản Samba từ 3.5.0 trở về sau đều có lỗ hổng thực thi đoạn mã từ xa, cho phép các máy client nhiễm độc tải nội dung lên thư mục dùng chung và khiến máy chủ tải rồi thực thi tập tin".  Liệu có phải đây là phiên bản Linux của lỗ hổng EternalBlue? Theo bộ tìm kiếm Shodan, hơn 485.000 máy tính cài đặt Samba sử dụng cổng 445 để truy cập Internet. Theo các nhà nghiên cứu tại Rapid 7, hơn 104.000 endpoint trên Internet chạy các phiên bản Samba có lỗ hổng, trong số đó 92.000 endpoint chạy các phiên bản Samba kh...

Tạo ứng dụng realtime với Firebase Database và ReactJS

Hello cả nhà ! Như các bạn cũng đã biết thì Firebase được tạo bởi "Ông lớn Google", bởi vậy lên việc sử dụng Firebase khá an toàn và tiên dụng. Mọi người có thể vô trang chủ của Firebase tại địa chỉ:  Firebase Google  . Firebase có rất nhiều tính năng vô cùng tuyệt vời như: Storage, Database, Hosting, Function, Authentication, ML Kit. Hôm nay mình xin phép làm một demo nhỏ cho tạo ứng dụng realtime bằng cách sử dụng Firebase Database với ReactJS . Bài viết này mình xin hướng dẫn các bước chuẩn bị trước khi vô code. Đầu tiên các bạn vô trang chủ của Firebase, và tới Firebase console. Sau khi vô tới Console Firebase các bạn nhấn vô Add a Project để tạo 1 dự án mới. Các bạn nhập tên cho project của mình,  nó sẽ tự random ID project cho các bạn theo tên của project mà các bạn đã đặt. Điền hoàn tất thì nhấn Tạo và chờ vài giây để cho nó tạo Thành công. Tạo project xong các bạn chọn tiếp tới tạo Database, và chúng ta cũng chỉ quan tâm đến nó ...