Python Programming Common Built In Functions And Methods Complete Guide
Understanding the Core Concepts of Python Programming Common Built in Functions and Methods
Python Programming Common Built-in Functions and Methods
Built-in Functions
print()
- Functionality: Displays output to the standard output device (usually the screen).
- Usage:
print("Hello, World!")
- Important Info: Supports multiple arguments, automatic conversion of non-string types to strings, and the flexibility to format strings using f-strings and the
format()
method.
len()
- Functionality: Returns the number of items in an object like a string, list, tuple, dictionary, or set.
- Usage:
len([1, 2, 3])
returns3
- Important Info: Efficiently calculates the length of the object without needing loops, making it ideal for performance-critical applications.
type()
- Functionality: Returns the type of the specified object.
- Usage:
type(5)
returns<class 'int'>
- Important Info: Useful for debugging and type assertions, enhancing the clarity and robustness of the code by allowing developers to check variable types.
input()
- Functionality: Takes user input from the standard input device (usually the keyboard).
- Usage:
name = input("Enter your name: ")
- Important Info: Always returns the input as a string, so type conversion may be necessary for non-string data types.
range()
- Functionality: Generates a sequence of numbers, often used in loops.
- Usage:
range(5)
returnsrange(0, 5)
equivalent to[0, 1, 2, 3, 4]
- Important Info: Efficiently creates sequences without storing the entire list in memory, making it suitable for large iterations.
sum()
- Functionality: Returns the sum of all items in an iterable or between two numbers.
- Usage:
sum([1, 2, 3])
returns6
- Important Info: Optimized for summing large sequences or numbers, making it ideal for mathematical operations and aggregations.
max() & min()
- Functionality: Returns the largest and smallest item in an iterable or the largest/smallest of two or more arguments, respectively.
- Usage:
max([1, 2, 3])
returns3
andmin([1, 2, 3])
returns1
- Important Info: Facilitates finding maximum and minimum values without needing custom comparison logic.
sorted()
- Functionality: Returns a new sorted list from the elements of any iterable.
- Usage:
sorted([3, 2, 1])
returns[1, 2, 3]
- Important Info: Can sort various data structures and supports custom sorting criteria through the key parameter.
enumerate()
- Functionality: Adds a counter to an iterable and returns it as an enumerate object.
- Usage:
list(enumerate(['a', 'b', 'c']))
returns[(0, 'a'), (1, 'b'), (2, 'c')]
- Important Info: Enhances loop control by providing simultaneous access to loop counters and iterable elements.
any() & all()
- Functionality: Check if any or all elements in an iterable are
True
. - Usage:
any([0, False, 2])
returnsTrue
andall([0, False, 2])
returnsFalse
- Important Info: Used for conditions involving multiple elements, offering compact and readable code.
- Functionality: Check if any or all elements in an iterable are
Common Methods
While built-in functions are global, methods are tied to specific data types. Here are some important methods associated with common Python data types:
List Methods
- append(item)
- Functionality: Adds an item to the end of the list.
- Usage:
my_list.append(4)
- extend(iterable)
- Functionality: Extends the list by appending all items from the iterable.
- Usage:
my_list.extend([4, 5, 6])
- insert(index, item)
- Functionality: Inserts an item at the specified index.
- Usage:
my_list.insert(1, 2)
- append(item)
String Methods
- upper() & lower()
- Functionality: Converts the string to uppercase or lowercase, respectively.
- Usage:
"hello".upper()
returns"HELLO"
- strip()
- Functionality: Removes leading and trailing whitespace characters.
- Usage:
" hello ".strip()
returns"hello"
- replace(old, new)
- Functionality: Replaces occurrences of the old substring with the new substring.
- Usage:
"hello world".replace("world", "universe")
returns"hello universe"
- upper() & lower()
Dictionary Methods
- keys()
- Functionality: Returns a view object displaying a list of the dictionary's keys.
- Usage:
my_dict.keys()
- values()
- Functionality: Returns a view object displaying a list of the dictionary's values.
- Usage:
my_dict.values()
- get(key, default=None)
- Functionality: Returns the value for the specified key. If the key is not found, returns the default value.
- Usage:
my_dict.get('key', 'default_value')
- keys()
Set Methods
- add(item)
- Functionality: Adds an element to the set.
- Usage:
my_set.add(1)
- remove(item)
- Functionality: Removes an element from the set; raises a KeyError if the element is not found.
- Usage:
my_set.remove(1)
- union(other_set)
- Functionality: Returns a new set with elements from both sets.
- Usage:
my_set.union({3, 4, 5})
- add(item)
Online Code run
Step-by-Step Guide: How to Implement Python Programming Common Built in Functions and Methods
Python Built-in Functions
1. print()
The print()
function outputs the specified message to the console.
# Example:
print("Hello, World!")
2. type()
The type()
function returns the type of the specified object.
# Example:
x = 5
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
3. len()
The len()
function returns the number of items in an object like a string, list, or tuple.
# Example:
text = "Python"
print(len(text)) # Output: 6
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
4. range()
The range()
function generates a sequence of numbers.
# Example:
for i in range(5):
print(i) # Outputs: 0 1 2 3 4
# Using range(start, stop, step)
for i in range(1, 6, 2):
print(i) # Outputs: 1 3 5
5. input()
The input()
function takes input from the user.
# Example:
name = input("Enter your name: ")
print(f"Hello {name}")
6. int()
, float()
, str()
These functions convert one data type to another.
# Example:
num_str = "10"
num_int = int(num_str)
print(num_int) # Output: 10 (as an integer)
num_float = float(num_str)
print(num_float) # Output: 10.0 (as a float)
num_back_to_str = str(num_int)
print(num_back_to_str) # Output: "10" (as a string)
7. list()
, tuple()
, set()
, dict()
These functions convert sequences (like strings, tuples, lists) into lists, tuples, sets, or dictionaries respectively.
# Example:
string_example = "hello"
list_example = list(string_example)
print(list_example) # Output: ['h', 'e', 'l', 'l', 'o']
tuple_example = (1, 2, 3)
list_from_tuple = list(tuple_example)
print(list_from_tuple) # Output: [1, 2, 3]
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
keys_values = [('key1', 'value1'), ('key2', 'value2')]
dictionary_example = dict(keys_values)
print(dictionary_example) # Output: {'key1': 'value1', 'key2': 'value2'}
8. max()
, min()
, sum()
These functions are used to find the maximum, minimum, and sum of a sequence respectively.
# Example:
numbers = [1, 5, 9, 2, 8]
print(max(numbers)) # Output: 9
print(min(numbers)) # Output: 1
print(sum(numbers)) # Output: 25
9. sorted()
The sorted()
function returns a new sorted list from the elements of any sequence.
# Example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# Sorting in reverse order
reverse_sorted_numbers = sorted(numbers, reverse=True)
print(reverse_sorted_numbers) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
10. abs()
The abs()
function returns the absolute value of a number, which is its distance from zero.
# Example:
number = -20
print(abs(number)) # Output: 20
Python String Methods
1. upper()
and lower()
The upper()
method converts all characters to uppercase, and lower()
method converts all characters to lowercase.
# Example:
greeting = "Hello, World!"
print(greeting.upper()) # Output: HELLO, WORLD!
print(greeting.lower()) # Output: hello, world!
2. strip()
, rstrip()
, lstrip()
These methods remove leading and trailing whitespaces.
# Example:
text = " Hello, World! "
print(text.strip()) # Output: "Hello, World!"
print(text.rstrip()) # Output: " Hello, World!"
print(text.lstrip()) # Output: "Hello, World! "
3. replace()
The replace()
method replaces a certain substring within a string.
# Example:
message = "Hi, I am Hi"
new_message = message.replace("Hi", "Hello")
print(new_message) # Output: "Hello, I am Hello"
4. split()
The split()
method splits a string into a list.
# Example:
sentence = "Hello, World!"
words = sentence.split(", ")
print(words) # Output: ["Hello", "World!"]
5. join()
The join()
method concatenates the elements of a list into a single string.
# Example:
words = ["Hello", "World!"]
sentence = ", ".join(words)
print(sentence) # Output: "Hello, World!"
6. find()
The find()
method returns the index of the first occurrence of the specified value.
# Example:
text = "Hello, World!"
index = text.find("World")
print(index) # Output: 7
Python List Methods
1. append()
The append()
method adds a single element to the end of the list.
# Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. remove()
The remove()
method removes the first occurrence of a value from the list.
# Example:
numbers = [1, 2, 2, 3, 4, 5]
numbers.remove(2)
print(numbers) # Output: [1, 2, 3, 4, 5]
3. pop()
The pop()
method removes the item at the specified index and returns it. If no index is specified, it removes the last item.
# Example:
numbers = [1, 2, 3, 4, 5]
popped_element = numbers.pop()
print(popped_element) # Output: 5
print(numbers) # Output: [1, 2, 3, 4]
popped_element_2 = numbers.pop(1)
print(popped_element_2) # Output: 2
print(numbers) # Output: [1, 3, 4]
4. insert()
The insert()
method inserts a specified value at the specified position.
# Example:
numbers = [1, 2, 4, 5]
numbers.insert(2, 3)
print(numbers) # Output: [1, 2, 3, 4, 5]
5. reverse()
The reverse()
method reverses the elements of the list in place.
# Example:
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
6. sort()
The sort()
method sorts the list in place and does not return anything.
# Example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# Sorting in reverse order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
Python Dictionary Methods
1. get()
The get()
method returns the value for a given key.
# Example:
person = {'name': 'John', 'age': 30}
print(person.get('name')) # Output: John
print(person.get('height')) # Output: None (since height is not a key)
print(person.get('height', 'Unknown')) # Output: Unknown
2. items()
The items()
method returns a view object displaying a list of a dictionary's key-value tuple pairs.
# Example:
person = {'name': 'John', 'age': 30}
for key, value in person.items():
print(f"{key}: {value}") # Output: name: John age: 30
3. keys()
The keys()
method returns a view object displaying a list of all keys in the dictionary.
# Example:
person = {'name': 'John', 'age': 30}
print(person.keys()) # Output: dict_keys(['name', 'age'])
4. values()
The values()
method returns a view object displaying a list of all values in the dictionary.
# Example:
person = {'name': 'John', 'age': 30}
print(person.values()) # Output: dict_values(['John', 30])
5. update()
The update()
method updates the dictionary with the elements from another dictionary object or from an iterable of key-value pairs.
Top 10 Interview Questions & Answers on Python Programming Common Built in Functions and Methods
1. len()
Question: How do you find the length of a list, string, or tuple in Python?
Answer: The len()
function is used to find the length of a sequence like a list, string, or tuple. For instance:
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
This code snippet returns the number of elements in my_list
.
2. range()
Question: What is the range()
function used for in Python?
Answer: The range()
function generates a sequence of numbers over a specified range. It's commonly used in loops. Here’s how it works:
for i in range(5):
print(i) # Output will be from 0 to 4 (not including 5)
This loop prints numbers from 0 up to, but not including, 5.
3. append()
Question: How can you add an element to the end of a list in Python?
Answer: The append()
method is used to add a single element to the end of a list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
4. extend()
Question: How do you add multiple elements to the end of a list?
Answer: The extend()
method is used to extend a list with another iterable (e.g., a list, tuple, or set).
my_list = [1, 2, 3]
additional_elements = [4, 5]
my_list.extend(additional_elements)
print(my_list) # Output: [1, 2, 3, 4, 5]
5. remove()
Question: How do you remove an element from a list in Python?
Answer: The remove()
method removes the first occurrence of a value from a list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2] (only the first '2' is removed)
6. pop()
Question: How do you retrieve and remove the last element from a list?
Answer: The pop()
method removes and returns the last item in a list unless an index is specified.
my_list = [1, 2, 3, 4]
last_element = my_list.pop()
print(last_element) # Output: 4
print(my_list) # Output: [1, 2, 3]
7. min() and max()
Question: How can you determine the minimum or maximum value in a list?
Answer: Use min()
and max()
functions to find the smallest and largest values in a list, respectively.
numbers = [5, 3, 8, 1, 9, 1]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
8. sum()
Question: How can you calculate the sum of all elements in a list of numbers?
Answer: The sum()
function adds up all the items in a numeric iterable (list, tuple).
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # Output: 15
9. type()
Question: How do you check the data type of a variable in Python?
Answer: The type()
function returns the type of an object.
my_var = 42
print(type(my_var)) # Output: <class 'int'>
my_other_var = "hello"
print(type(my_other_var)) # Output: <class 'str'>
10. sort() and sorted()
Question: How do you sort a list of elements in Python?
Answer: The sort()
method sorts a list in place, while the sorted()
function returns a new sorted list. Both can take arguments like reverse
to determine sorting direction.
Login to post a comment.