+ 1

best description to understand difference between function and method in List with an example

best description to understand difference between function and method used in List of python with an example

9th Feb 2023, 11:15 AM
Sravan
2 Answers
+ 2
Functions and methods are similar in that they both perform a specific task, but they are used differently in Python. A function is a block of reusable code that takes one or more inputs (also called arguments) and returns an output. Functions can be called anywhere in a program and can be used to perform a wide range of tasks. For example: def square(x): return x**2 result = square(5) print(result) # 25
9th Feb 2023, 12:21 PM
ArsenicolupinIII
+ 2
A method, on the other hand, is a function that is associated with an object and is called on that object. Methods are specific to the object and perform actions that relate to that object. For example: numbers = [1, 2, 3, 4, 5] numbers.append(6) print(numbers) # [1, 2, 3, 4, 5, 6] In this example, the "append()" method is called on the list object "numbers", which adds the element "6" to the end of the list.
9th Feb 2023, 12:22 PM
ArsenicolupinIII