[Introduction to python] Function
List Functions
The append() function is used to add an item to the end of the list:
nums = [1, 2, 3]
nums.append(4)
print(nums)
=>
[1, 2, 3, 4]
-
insert() inserts a new item at the given position in the list:
words = ["Python", "fun"]
words.insert(1, "is")
print(words)
=>
['Python', 'is', 'fun']
-
index() finds the first occurrence of a list item and returns its index.
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(letters.index('p'))
print(letters.index('q'))
=>
2
0
1
-
list.count(item): Returns a count of how many times an item occurs in a list.
list.remove(item): Removes an item from a list.
list.reverse(): Reverses items in a list.
x = [2, 4, 6, 2, 7, 2, 9]
print(x.count(2))
x.remove(4)
print(x)
x.reverse()
print(x)
=>
3
[2, 6, 2, 7, 2, 9]
[9, 2, 7, 2, 6, 2]
-
String Formatting
Strings have a format() function, which enables values to be embedded in it, using placeholders.
nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
print(msg)
=>
Numbers: 4 5 6
-
You can also name the placeholders, instead of the index numbers.
a = "{x}, {y}".format(x=5, y=12)
print(a)
=>
5, 12
-
-
join() joins a list of strings with another string as a separator.
x = ", ".join(["spam", "eggs", "ham"])
print(x)
#prints "spam, eggs, ham"
=>
spam, eggs, ham
-\
String Functions
split() is the opposite of join(). It turns a string with a certain separator into a list.
str = "some text goes here"
x = str.split(' ')
print(x)
=>
['some', 'text', 'goes', 'here']
-
replace() replaces one substring in a string with another.
x = "Hello ME"
print(x.replace("ME", "world"))
=>
Hello world
-
lower() and upper() change the case of a string to lowercase and uppercase.
print("This is a sentence.".upper())
print("AN ALL CAPS SENTENCE".lower())
=>
THIS IS A SENTENCE.
an all caps sentence
-
Remember, strings are also lists. What is the output of this code?
txt = "hello"
print(max(txt))
You can create your own functions by using the def statement.
Here’s an example of a function named my_func. It takes no arguments, and prints "spam" three times.
def my_func():
print("spam")
print("spam")
print("spam")
-
Arguments
Functions can take arguments, which can be used to generate the function output.
def exclamation(word):
print(word + "!")
exclamation("spam")
=>
spam!
-