LATTEOTW

  • Range

    From Python official document:

    class range(stop)

    class range(start, stop[, step])

    Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types >— list, tuple, range.

    Range is a little bit different than all other built-in functions. It’s essential a data type that’s built-in in Python. More specifically, it shares the same feature of list and tuple - it’s sequential. Let’s introduce some features and usage of range.

    • Start is inclusive and stop is exclusive

      1
      2
      for i in range(1, 3, 1):
      print(i)

      This will print:

      1
      2
      1
      2
    • You can ignore step parameter. When step is ignored, it defaults to 1

      1
      2
      for i in range(1, 3):
      print(i)

      This will print the same as above

    • You can ignore both start and step. When start is ignored, it defaults to 0

      1
      2
      for i in range(3):
      print(i)

      This will print:

      1
      2
      3
      0
      1
      2

      There are more advanced usage of range is discussed at this post.

  • reversed()

    Python3 has reversed() as a built-in function which takes a seq as input. According to Python’s official documentation

    seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).

    One thing to notice is that reversed() return an iterator. To make the iterator a list, you have co explicitly cast it. For example:

    1
    2
    3
    4
    5
    6
    >>> a = [1, 2, 3]
    >>> b = reversed(a)
    >>> b
    <list_reverseiterator object at 0x1090762e8>
    >>> list(b)
    [3, 2, 1]

    It has O(N) time and space complexity.

  • sorted()

    The function signature of the python built-in sorted() function is the following:
    sorted(iterable, *, key=None, reverse=False)

    I would highly suggest you to read this official Sorting HOW TO article from Python team.


 Comments


Copyright © 2020 LATTEOTW

Use Material X as theme. Total visits times