Pythonic ways

What is bool?

Implicit boolean value of a empty list

a = []
if not a:
    print('a is empty')

List

[] slicing notation

Slicing with a[start:end]

it will return an list of elem from a[start] till a[end – 1]. If start > end then return an empty string. Very good to know for boundary checks. Also works for string. We can omit both start and end and that will return a copy of the whole array.

To make a copy of 2d array

copy_a = [row[:] for row in origin_a]

Negative index

start or and can be negative. It will count from the end. a[-1] is the last element a[-2:] will return the last two element. a[:-2] everything except the last two

Negative steps:

a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed

a[1::-1] means start at index 1 and go till 0, where 0 is right before the end. a[:-3:-1] means we will start from 0 and go back till right before the third last(so the last two reversed).

[ : : ]

These two links are really helpful Stackoverflow Yeah we don’t code anymore. Just move codes around

Copy list

List is mutable so through pass by assignment, a = b will just pass b’s handle to a. If we want to copy, we can use a = b[:] where b[:] will return a copy of the whole list

String

strip all chars

Using join

First we need to find all possible punctuation:

import string
exclude = set(string.punctuation)

set will create element for each and every char in string.punctuation.

Then we will remake the given string using join.

new_s = ''.join(c for c in old_str if c not in exclude)

We will join an empty string with all char in the old string that’s not in exlude (aka not punctuation)

We can remove whitespace as well by adding and c != ‘ ‘.

Using translate

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

This use translate and will perform a row string operation in C. Not gonna beat it in spead.

Reverse a string (array)

s = s[::-1]

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax