Python Useful Functions and Methods

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Container Types in Python
Dictionaries: Keeping track of pairs
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Lists in Python.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Introduction to Python By Neil Cook Twitter: njcuk Slides/Notes:
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Higher Order Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Python Sets and Dictionaries Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Set properties What is a set? A set is a mutable.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Fundamentals of Programming I Higher-Order Functions
Higher Order Functions
Advanced Python Idioms
CS1022 Computer Programming & Principles
ITCS-3190.
Algorithmic complexity: Speed of algorithms
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
Intro To Pete Alonzi University of Virginia Library
Department of Computer Science,
Python Useful Functions and Methods
Core libraries Scripts, by default only import sys (various system services/functions) and builtins (built-in functions, exceptions and special objects.
Lecture 10 Data Collections
Ruth Anderson CSE 140 University of Washington
Python for Quant Finance
Python Primer 2: Functions and Control Flow
CISC101 Reminders Slides have changed from those posted last night…
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Transforming Data (Python®)
Python Useful Functions and Methods
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Test Automation For Web-Based Applications
Web DB Programming: PHP
Ruth Anderson UW CSE 160 Winter 2017
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Algorithmic complexity: Speed of algorithms
Topics Sequences Introduction to Lists List Slicing
Python Primer 1: Types and Operators
Michael Ernst CSE 140 University of Washington
(more) Python.
Lambda Functions, MapReduce and List Comprehensions
Advanced Python Idioms
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Algorithmic complexity: Speed of algorithms
Python Sets and Dictionaries
Advanced Python Idioms
Ruth Anderson CSE 160 University of Washington
Topics Sequences Introduction to Lists List Slicing
Python Review
Ruth Anderson UW CSE 160 Spring 2018
Winter 2019 CISC101 5/30/2019 CISC101 Reminders
More Basics of Python Common types of data we will work with
Python Simple file reading
Introduction to PYTHON
Ruth Anderson UW CSE 160 Winter 2016
An Introduction to Data Science using Python
An Introduction to Data Science using Python
Presentation transcript:

Python Useful Functions and Methods Peter Wad Sackett

Nothing more to learn ? There are quite a few built-in functions not mentioned yet, see https://docs.python.org/3/library/functions.html So far has been mentioned 15 out of 68: dict(), float(), format(), input(), int(), isinstance(), len(), list(), open(), print(), range(), reversed(), set(), sorted(), str() and tuple() Many of the unmentioned functions works with python’s object model or the inner workings of python. Useful for advanced python code. Classes for making your own python objects, with methods working on them.

Nice to know built-in functions The following are nice to know for a beginner: abs(number) returns absolute value of a number dir(object) returns info on an object enumerate(iterable) returns an enumerated list of tuples help(string) returns help in the subject given id(object) returns the id of an object, guaranteed to be unique iter(iterable) returns an iterable – dicts as key/value tuples max(iterable) returns the maximum value min(iterable) returns the minimum value round(number) rounds a number sum(iterable) returns the sum of the iterable zip(iterables) returns a list of tubles of the input in ”pairs”

New built-in data types The type bytes is similar to strings; immutable and supports all string methods. Efficient, uses the ascii charset, seems like a list of numbers. name = b’Peter’ # the b denotes a bytes type print(name[0]) #result: 80 The type bytearray is like mutable strings and supports all string methods. It is more efficient when your strings change. It seems like a list of numbers that can’t hold a value bigger than 255, just like bytes. name = bytearray(b’Peter’) name[2] = 100 # change t to d The type frozenset is a immutable set and supports all set methods, that does not change the frozenset, obviously. Can be used as keys in dicts and sets. Frozensets are to sets, what tuples are to lists or bytes to bytearrays. fruits = frozenset(’apple’, ’banana’, ’cherry’, ’date’)

New sequence method sequencetype.count(item) returns the number of occurrences. This can be used to count nucleotides in DNA. DNA = ’TGCACTCGACTCAGATCGACTACG’ A_count = DNA.count(’A’) T_count = DNA.count(’T’) Due to the fast performance of the method, it is faster to count 4 times (where each count is an iteration over the DNA-string), than to make a standard for loop and count all bases in a single iteration over the string. Since all sequencetypes support the count method, it can also be used with lists, tuples, bytes, bytearray, etc.

Python concepts on iteration This overview of various iteration concepts will be explored on the next slides. Figure by Vincent Driessen

Concepts - iteration A container is ”holding data” – typically lists, sets, dict or strings. What defines a container is that it can be queried for membership of an element – does it contain the element. An iterable is often a container but can also be an open file or other object that can return an iterator. An iterator is stateful helper object. It keeps track of the iteration over the iterable. It can be created by using the iter() function call on an iterable. It is created automatically in for loops. # The container, but also the iterable numbers = [1, 2, 3] # Creating two iterators iter1 = iter(numbers) iter2 = iter(numbers) # Using the next function call – non-looping iteration next(iter1) # gives 1 next(iter1) # gives 2 next(iter2) # gives 1 next(iter1) # gives 3 next(iter1) # raises the exception StopIteration

Lambda, the anonymous function The lambda is a small anonymous function which can be put any place, where a function is required. It has been put into Python to support functional programming. Here shown with method sort: names = [’Aiz’, ’Cain’, ’Gemini’, ’Zenia’] # The names shold be sorted according to the last letter names.sort(key=lambda x: x[-1]) # Result: [’Zenia’, ’Gemini’, ’Cain’, ’Aiz’] It is equal to: def lastChar(myStr): return myStr[-1] names.sort(key=lastChar) The generel syntax of the lambda is: lambda argument_list: expression lambda x,y: x*y-4

Lambda, map and filter – equal to comprehension The lambda function is most often used together with the functions map and filter, which both return an iterator. By applying the list function on an iterator a list will be returned. This has been previously shown/used in sets and dicts. The map and filter function will perform the given function on the entire sequence and return the result: map(function, sequence) filter(function, sequence) Using lambda/map to take a list of names and reverse the spelling and create a new list. The comprehension way is also shown. reverse_names = list(map(lambda x: x[::-1], names)) reverse_names = [ x[::-1] for x in names ] The filter function is choosing which elements to keep. The lambda function is used to make a True/False evaluation of each element, so the filter can pick it – or not. a_names = list(filter(lambda x: ’a’ in x, names)) a_names = [ x for x in names if ’a’ in x ]

Standard libraries Python has many standard libraries, far too many to memorize. Look them up, when you need something. https://docs.python.org/3/library/ Each library contains several functions, all relevant and appropriate to the core functionality of the library. You won’t find string functions in the math library. In the course the following standard libraries have been used: string – string operations re – regular expressions math – mathmatical functions os – operating system interfaces sys – system specific functions Some new ones which are surprisingly often useful: random – pseudo random numbers copy – shallow and deep copy operations argparse – parsing arguments/options from command line

Scientific libraries Python also has many scientific libraries. They are part of what makes Python great. You can get most with the free Anaconda distribution. https://www.anaconda.com/download/ To mention some of the most wellknown libraries: NumPy – support for large multi-dimensional matrices plus large collection of high-level mathematical functions. Matplotlib – plotting graphs. pandas – data manipulation and analysis. SymPy – symbolic computation. tensorflow – machine learning sklearn – machine learning SciPy – meta package including many of above libraries plus more.