Python tips

1. collections.Counter lets you find the most common elements in an iterable:

>>> import collections
>>> c = collections.Counter('helloworld')

>>> c
Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})

>>> c.most_common(3)
[('l', 3), ('o', 2), ('e', 1)]

2.

>>> import antigravity

in python console will take you to XKCD site.

3. Reversing lists in python

Option 1: Reversing a List In-Place With the list.reverse() Method

>>> mylist = [1, 2, 3, 4, 5]
>>> mylist
[1, 2, 3, 4, 5]

>>> mylist.reverse()
None

>>> mylist
[5, 4, 3, 2, 1]

Option 2: Using the “[::-1]” Slicing Trick to Reverse a Python List

>>> mylist
[1, 2, 3, 4, 5]

>>> mylist[::-1]
[5, 4, 3, 2, 1]

Option 3: reversed()

Python’s built-in reversed() function allows you to create a reverse iterator for an existing list or sequence object. This is a flexible and clean solution that relies on some advanced Python features—but it remains readable due to the clear naming of the reversed() function.

>>> lst = [1, 2, 3, 4, 5]
>>> list(reversed(lst))
[5, 4, 3, 2, 1]

4. Python list slice syntax fun

You can clear all elements from a list:

>>> lst = [1, 2, 3, 4, 5]
>>> del lst[:]
>>> lst
[]

You can replace all elements of a list without creating a new list object:

>>> a = lst
>>> lst[:] = [7, 8, 9]
>>> lst
[7, 8, 9]
>>> a
[7, 8, 9]
>>> a is lst
True

You can also create a (shallow) copy of a list:

>>> b = lst[:]
>>> b
[7, 8, 9]
>>> b is lst
False

5. Python 3.5+ type annotations

def my_add(a: int, b: int) -> int:
    return a + b

6. How To Check if a File or Directory Exists?

See if file exists:

Method1

import os
os.path.exists()

Calling os.path.exists() will return True for files and directories if they exist.

os.path.isfile()

If you want to ensure that a given path points to a file and not to a directory, you can use the os.path.isfile() function.
With both functions it’s important to keep in mind that they will only check if a file exists—and not if the program actually has access to it. If verifying access is important then you should consider simply opening the file while looking out for an I/O exception (IOError) to be raised. Alternatively, you can use the os.access() function in the standard library to check whether a file exists and is accessible at the same time. This would be more similar to using the os.path.exists() function for checking if a file exists.

Method2

open()
try..except(IOError/FileNotFoundError)

Method3

pathlib.Path.exists() and
pathlib.Path.is_file()

For video, see here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s