Made by Mohit Samant. Contact: [Link]@somaiya.
edu
Python Built-in Functions Reference
Lists, Strings, Dictionaries, Sets & Tuples
Contents
1 Lists 2
1.1 Basic Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Adding and Removing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Transforming Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2 Strings 6
2.1 Basic Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Case and Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Modifying Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5 Splitting and Joining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.6 Type Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3 Dictionaries 10
3.1 Basic Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.2 Adding, Updating, Removing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 Searching and Transforming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4 Sets 12
4.1 Basic Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Adding and Removing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.3 Set Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5 Tuples 14
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
1 Lists
1.1 Basic Properties
len(lst)
Returns the number of elements in the list.
numbers = [1 , 2 , 3]
print ( len ( numbers ) ) # 3
not lst
Returns True if the list is empty. There is no dedicated isEmpty method in Python; an empty
list is "falsy".
numbers = []
print ( not numbers ) # True
print ( len ( numbers ) == 0) # True
lst[0] and lst[-1]
Access the first and last elements using indexing. Negative indices count from the end.
numbers = [10 , 20 , 30]
print ( numbers [0]) # 10
print ( numbers [ -1]) # 30
1.2 Adding and Removing Elements
.append(x)
Adds a new element to the end of the list.
numbers = [1 , 2 , 3]
numbers . append (4)
print ( numbers ) # [1 , 2 , 3 , 4]
.insert(i, x)
Inserts a new element at the specified index.
numbers = [1 , 2 , 4]
numbers . insert (2 , 3)
print ( numbers ) # [1 , 2 , 3 , 4]
.remove(x)
Removes the first occurrence of the given value. Raises ValueError if not found.
numbers = [1 , 2 , 3 , 2]
numbers . remove (2)
print ( numbers ) # [1 , 3 , 2]
2
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
.pop() / .pop(i)
Removes and returns the last element, or the element at index i if given.
numbers = [1 , 2 , 3]
last = numbers . pop ()
print ( last ) # 3
print ( numbers ) # [1 , 2]
first = numbers . pop (0)
print ( first ) # 1
print ( numbers ) # [2]
.clear()
Removes all elements from the list.
numbers = [1 , 2 , 3]
numbers . clear ()
print ( numbers ) # []
.extend(iterable)
Appends all elements from another iterable to the end of the list.
numbers = [1 , 2]
numbers . extend ([3 , 4])
print ( numbers ) # [1 , 2 , 3 , 4]
1.3 Searching
x in lst
Returns True if the list contains the given element.
numbers = [1 , 2 , 3]
print (2 in numbers ) # True
.index(x)
Returns the index of the first matching element. Raises ValueError if not found.
letters = [ " a " , " b " , " c " ]
print ( letters . index ( " b " ) ) # 1
.count(x)
Returns the number of times x appears in the list.
numbers = [1 , 2 , 2 , 3 , 2]
print ( numbers . count (2) ) # 3
3
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
min(lst) / max(lst)
Returns the smallest / largest element of the list.
numbers = [5 , 2 , 9 , 1]
print ( min ( numbers ) ) # 1
print ( max ( numbers ) ) # 9
1.4 Transforming Lists
sorted(lst)
Returns a new list with elements sorted in ascending order.
numbers = [5 , 2 , 9 , 1]
print ( sorted ( numbers ) ) # [1 , 2 , 5 , 9]
.sort()
Sorts the list in place (mutating). Returns None.
numbers = [5 , 2 , 9 , 1]
numbers . sort ()
print ( numbers ) # [1 , 2 , 5 , 9]
reversed(lst) / lst[::-1]
Returns the elements in reverse order.
numbers = [1 , 2 , 3]
print ( list ( reversed ( numbers ) ) ) # [3 , 2 , 1]
print ( numbers [:: -1]) # [3 , 2 , 1]
map(func, lst)
Applies a function to every element, returning a map object (usually wrapped in list()).
numbers = [1 , 2 , 3]
doubled = list ( map ( lambda x : x * 2 , numbers ) )
print ( doubled ) # [2 , 4 , 6]
List comprehension
The idiomatic Python way to transform a list, equivalent to map.
numbers = [1 , 2 , 3]
doubled = [ x * 2 for x in numbers ]
print ( doubled ) # [2 , 4 , 6]
filter(func, lst)
Returns a filter object containing elements for which the function returns True.
4
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
numbers = [1 , 2 , 3 , 4 , 5]
evens = list ( filter ( lambda x : x % 2 == 0 , numbers ) )
print ( evens ) # [2 , 4]
Filtering with a comprehension
The idiomatic Python way to filter a list, equivalent to filter.
numbers = [1 , 2 , 3 , 4 , 5]
evens = [ x for x in numbers if x % 2 == 0]
print ( evens ) # [2 , 4]
[Link](func, lst)
Combines all elements into a single value using a function. Not a builtin; import from functools.
from functools import reduce
numbers = [1 , 2 , 3 , 4]
total = reduce ( lambda acc , x : acc + x , numbers )
print ( total ) # 10
enumerate(lst)
Returns an iterator of (index, element) pairs.
fruits = [ " apple " , " banana " ]
for index , fruit in enumerate ( fruits ) :
print ( f " { index }: { fruit } " )
# 0: apple
# 1: banana
zip(lst1, lst2)
Combines two or more iterables element-wise into tuples.
names = [ " Alice " , " Bob " ]
ages = [30 , 25]
for name , age in zip ( names , ages ) :
print ( f " { name } is { age } " )
# Alice is 30
# Bob is 25
1.5 Slicing
lst[start:stop]
Returns a shallow copy of a portion of the list.
numbers = [1 , 2 , 3 , 4 , 5]
print ( numbers [1:3]) # [2 , 3]
print ( numbers [:3]) # [1 , 2 , 3]
print ( numbers [3:]) # [4 , 5]
5
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
lst[start:stop:step]
Slicing with a step, useful for taking every nth element or reversing.
numbers = [1 , 2 , 3 , 4 , 5]
print ( numbers [::2]) # [1 , 3 , 5]
print ( numbers [:: -1]) # [5 , 4 , 3 , 2 , 1]
del lst[start:stop]
Deletes a slice of elements from the list in place.
numbers = [1 , 2 , 3 , 4 , 5]
del numbers [1:3]
print ( numbers ) # [1 , 4 , 5]
1.6 Aggregate Functions
sum(lst)
Returns the sum of all elements in the list.
numbers = [1 , 2 , 3 , 4]
print ( sum ( numbers ) ) # 10
any(lst) / all(lst)
Returns True if any / all elements are truthy.
numbers = [0 , 1 , 2]
print ( any ( numbers ) ) # True ( at least one truthy )
print ( all ( numbers ) ) # False (0 is falsy )
2 Strings
2.1 Basic Properties
len(s)
Returns the number of characters in the string.
s = " Python "
print ( len ( s ) ) # 6
not s
Returns True if the string is empty.
s = ""
print ( not s ) # True
6
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
2.2 Case and Formatting
.upper()
Returns an uppercase copy of the string.
s = " hello "
print ( s . upper () ) # " HELLO "
.lower()
Returns a lowercase copy of the string.
s = " HELLO "
print ( s . lower () ) # " hello "
.capitalize()
Returns a copy with only the first character capitalized.
s = " python programming "
print ( s . capitalize () ) # " Python programming "
.title()
Returns a copy with the first letter of each word capitalized.
s = " python programming "
print ( s . title () ) # " Python Programming "
.strip()
Removes leading and trailing whitespace (or given characters).
s = " Hello "
print ( s . strip () ) # " Hello "
.lstrip() / .rstrip()
Removes whitespace from only the left / right side of the string.
s = " Hello "
print ( s . lstrip () ) # " Hello "
print ( s . rstrip () ) # " Hello "
2.3 Searching
substring in s
Returns True if the string contains the given substring.
s = " Hello , World ! "
print ( " World " in s ) # True
7
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
.startswith(prefix)
Returns True if the string starts with the given prefix.
s = " Hello , World ! "
print ( s . startswith ( " Hello " ) ) # True
.endswith(suffix)
Returns True if the string ends with the given suffix.
s = " Hello , World ! "
print ( s . endswith ( " ! " ) ) # True
.find(sub)
Returns the lowest index of the substring, or -1 if not found.
s = " Hello , World ! "
print ( s . find ( " World " ) ) # 7
print ( s . find ( " Swift " ) ) # -1
.index(sub)
Like .find() but raises ValueError instead of returning -1.
s = " Hello , World ! "
print ( s . index ( " World " ) ) # 7
.count(sub)
Returns the number of non-overlapping occurrences of a substring.
s = " abcabcabc "
print ( s . count ( " abc " ) ) # 3
2.4 Modifying Strings
Strings in Python are immutable, so these methods always return a new string rather than
modifying the original in place.
.replace(old, new)
Returns a new string with all occurrences of a substring replaced.
s = " Hello , World ! "
new_s = s . replace ( " World " , " Python " )
print ( new_s ) # " Hello , Python !"
.zfill(width)
Pads the string with leading zeros to reach the given width.
8
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
s = " 42 "
print ( s . zfill (5) ) # "00042"
.ljust(w) / .rjust(w) / .center(w)
Pads the string to the given width, aligned left, right, or centered.
s = " hi "
print ( s . ljust (6 , " -" ) ) # " hi - - - -"
print ( s . rjust (6 , " -" ) ) # " - - - - hi "
print ( s . center (6 , " -" ) ) # " - - hi - -"
2.5 Splitting and Joining
.split(sep)
Splits a string into a list of substrings using a separator (default: whitespace).
csv = " one , two , three "
parts = csv . split ( " ," )
print ( parts ) # [ ’ one ’, ’ two ’, ’ three ’]
.join(iterable)
Joins an iterable of strings into a single string, using this string as the separator.
words = [ " Hello " , " World " ]
print ( " " . join ( words ) ) # " Hello World "
.splitlines()
Splits a string at line breaks and returns a list of lines.
text = " line1 \ nline2 \ nline3 "
print ( text . splitlines () ) # [ ’ line1 ’, ’ line2 ’, ’ line3 ’]
s[::-1]
Reverses a string using extended slicing (there is no built-in .reverse() for strings).
s = " Python "
print ( s [:: -1]) # " nohtyP "
2.6 Type Checks
.isdigit() / .isalpha() / .isalnum()
Check whether the string consists only of digits, letters, or alphanumeric characters.
9
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
print ( " 123 " . isdigit () ) # True
print ( " abc " . isalpha () ) # True
print ( " abc123 " . isalnum () ) # True
f-strings
The idiomatic way to format values into a string.
name = " Alice "
age = 30
print ( f " { name } is { age } years old " )
# " Alice is 30 years old "
3 Dictionaries
3.1 Basic Properties
len(d)
Returns the number of key-value pairs.
ages = { " Alice " : 30 , " Bob " : 25}
print ( len ( ages ) ) # 2
not d
Returns True if the dictionary has no key-value pairs.
d = {}
print ( not d ) # True
.keys()
Returns a view of the dictionary’s keys.
ages = { " Alice " : 30 , " Bob " : 25}
print ( list ( ages . keys () ) ) # [ ’ Alice ’, ’ Bob ’]
.values()
Returns a view of the dictionary’s values.
ages = { " Alice " : 30 , " Bob " : 25}
print ( list ( ages . values () ) ) # [30 , 25]
.items()
Returns a view of (key, value) pairs.
10
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
ages = { " Alice " : 30 , " Bob " : 25}
for key , value in ages . items () :
print ( key , value )
# Alice 30
# Bob 25
3.2 Adding, Updating, Removing
d[key] = value
Adds a new key-value pair, or updates the value if the key already exists.
ages = { " Alice " : 30}
ages [ " Bob " ] = 25
print ( ages ) # { ’ Alice ’: 30 , ’ Bob ’: 25}
.get(key, default)
Returns the value for a key, or a default value (or None) if the key is absent. Never raises
KeyError.
ages = { " Alice " : 30}
print ( ages . get ( " Bob " , 0) ) # 0
.pop(key)
Removes the given key and returns its value. Raises KeyError if absent (unless a default is
given).
ages = { " Alice " : 30 , " Bob " : 25}
removed = ages . pop ( " Bob " )
print ( removed ) # 25
print ( ages ) # { ’ Alice ’: 30}
.update(other)
Merges another dictionary into this one, overwriting existing keys.
ages = { " Alice " : 30}
ages . update ({ " Alice " : 99 , " Bob " : 25})
print ( ages ) # { ’ Alice ’: 99 , ’ Bob ’: 25}
.setdefault(key, default)
Returns the value for a key, inserting it with the default if absent.
ages = { " Alice " : 30}
ages . setdefault ( " Bob " , 25)
print ( ages ) # { ’ Alice ’: 30 , ’ Bob ’: 25}
11
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
del d[key]
Removes the key-value pair for the given key. Raises KeyError if absent.
ages = { " Alice " : 30 , " Bob " : 25}
del ages [ " Bob " ]
print ( ages ) # { ’ Alice ’: 30}
3.3 Searching and Transforming
key in d
Returns True if the dictionary contains the given key.
ages = { " Alice " : 30 , " Bob " : 25}
print ( " Alice " in ages ) # True
Dictionary comprehension
The idiomatic way to build a new dictionary from an existing one.
ages = { " Alice " : 30 , " Bob " : 25}
in_ten_years = { k : v + 10 for k , v in ages . items () }
print ( in_ten_years ) # { ’ Alice ’: 40 , ’ Bob ’: 35}
sorted([Link]())
Returns the dictionary’s items sorted, e.g. by key or by value.
ages = { " Bob " : 25 , " Alice " : 30}
by_age = sorted ( ages . items () , key = lambda item : item [1])
print ( by_age ) # [( ’ Bob ’, 25) , ( ’ Alice ’, 30) ]
4 Sets
4.1 Basic Properties
len(s)
Returns the number of elements in the set.
s = {1 , 2 , 3}
print ( len ( s ) ) # 3
not s
Returns True if the set contains no elements.
s = set ()
print ( not s ) # True
12
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
4.2 Adding and Removing
.add(x)
Adds an element to the set (no effect if already present).
s = {1 , 2 , 3}
s . add (4)
print ( s ) # {1 , 2 , 3 , 4}
.remove(x)
Removes an element from the set. Raises KeyError if not present.
s = {1 , 2 , 3}
s . remove (2)
print ( s ) # {1 , 3}
.discard(x)
Removes an element if present; does nothing (no error) if absent.
s = {1 , 2 , 3}
s . discard (5)
print ( s ) # {1 , 2 , 3}
.pop()
Removes and returns an arbitrary element from the set.
s = {1 , 2 , 3}
x = s . pop ()
print ( x in {1 , 2 , 3}) # True
x in s
Returns True if the set contains the given element.
s = {1 , 2 , 3}
print (2 in s ) # True
4.3 Set Algebra
.union(other)
Returns a new set with all elements from both sets.
a = {1 , 2 , 3}
b = {3 , 4 , 5}
print ( a . union ( b ) ) # {1 , 2 , 3 , 4 , 5}
print ( a | b ) # {1 , 2 , 3 , 4 , 5}
13
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
.intersection(other)
Returns a new set with elements common to both sets.
a = {1 , 2 , 3}
b = {2 , 3 , 4}
print ( a . intersection ( b ) ) # {2 , 3}
print ( a & b ) # {2 , 3}
.difference(other)
Returns a new set with elements in the first set but not the second.
a = {1 , 2 , 3}
b = {2 , 3}
print ( a . difference ( b ) ) # {1}
print ( a - b ) # {1}
.symmetric_difference(other)
Returns elements in either set, but not both.
a = {1 , 2 , 3}
b = {3 , 4 , 5}
print ( a . s y m m e t r i c _ d i f fe r e n c e ( b ) ) # {1 , 2 , 4 , 5}
print ( a ^ b ) # {1 , 2 , 4 , 5}
.issubset(other) / .issuperset(other)
Checks whether one set’s elements are contained in (or contain) another.
a = {1 , 2}
b = {1 , 2 , 3}
print ( a . issubset ( b ) ) # True
print ( b . issuperset ( a ) ) # True
.isdisjoint(other)
Returns True if the two sets share no elements.
a = {1 , 2}
b = {3 , 4}
print ( a . isdisjoint ( b ) ) # True
5 Tuples
5.1 Overview
Tuples group multiple values into a single, immutable, ordered collection. They support only a
couple of methods, but Python provides convenient built-in ways to access, unpack, and compare
them.
Positional access
14
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
Access tuple elements by their zero-based index, just like a list.
person = ( " Alice " , 30)
print ( person [0]) # " Alice "
print ( person [1]) # 30
Immutability
Tuples cannot be modified after creation; attempting to assign raises TypeError.
person = ( " Alice " , 30)
% person [0] = " Bob " % TypeError : ’ tuple ’ object does not support
% item assignment
Unpacking
Unpack a tuple’s values directly into individual variables.
name , age = ( " Alice " , 30)
print ( name ) # " Alice "
print ( age ) # 30
Ignoring values with _
Use an underscore to skip elements you do not need.
name , _ = ( " Alice " , 30)
print ( name ) # " Alice "
Returning multiple values from a function
A common use of tuples: returning several related values at once.
def min_max ( numbers ) :
return min ( numbers ) , max ( numbers )
lo , hi = min_max ([4 , 9 , 1 , 7])
print ( lo ) # 1
print ( hi ) # 9
.count(x) / .index(x)
Counts occurrences of a value, or finds the index of its first occurrence.
t = (1 , 2 , 2 , 3)
print ( t . count (2) ) # 2
print ( t . index (3) ) # 3
[Link]
Creates a tuple subclass with named fields for clearer, self-documenting access.
15
Made by Mohit Samant. Contact: [Link]@[Link]
Made by Mohit Samant. Contact: [Link]@[Link]
from collections import namedtuple
Person = namedtuple ( " Person " , [ " name " , " age " ])
person = Person ( name = " Alice " , age =30)
print ( person . name ) # " Alice "
print ( person . age ) # 30
Comparing tuples with ==
Tuples are compared element-by-element, left to right.
a = (1 , " apple " )
b = (1 , " apple " )
print ( a == b ) # True
16
Made by Mohit Samant. Contact: [Link]@[Link]