Methods Flashcards
How do find out more information about a method?
help(mylist.insert)
What is a method?
Methods are essentially functions built into objects
What is an object?
An object is simply a collection of data (variables) and methods (functions) that act on those data.
What is .append()?
Give an example
append() allows us to add elements to the end of a list:
1st = [1,2,3,4,5]
1st.append(6)
OUTPUT
[1, 2, 3, 4, 5, 6]
What is .count()?
Give an example
The count() method will count the number of occurrences of an element in a list.
1st = [1,2,3,4,5]
1st.count(2)
OUTPUT
1
What is .split()?
Give an example
Splits a string in a list item
txt = “welcome to the jungle”
x = txt.split()
print(x)
print(x[0])
print(x[0][1])
print(x[:2])
OUTPUT
[‘welcome’, ‘to’, ‘the’, ‘jungle’]
welcome
e
[‘welcome’, ‘to’]
What is .join()?
Give example
The .join() method allows you to join together strings in a list with some connector string. For example, some uses of the .join() method:
numList = [‘1’, ‘2’, ‘3’, ‘4’]
separator = ‘, ‘
print(separator.join(numList))
This means if you had a list of words you wanted to turn back into a sentence, you could just join them with a single space string:
Example 2:
> > > print(“ “.join([‘Hello’, ‘world’])
OUTPUT
Hello world