Passing Mutable Objects


The same object in the memory is referred by both

list_a
and
list_x

Code

def add_item(list_x):
list_x += [3]
list_a = [1,2]
add_item(list_a)
print(list_a)
PYTHON

Output

[1, 2, 3]

Code

def add_item(list_x):
list_x = list_x + [3]
list_a = [1,2]
add_item(list_a)
print(list_a)
PYTHON

Output

[1, 2]

Default args are evaluated only once when the function is defined, not each time the function is called.

Code

def add_item(list_x=[]):
list_x += [3]
print(list_x)
add_item()
add_item([1,2])
add_item()
PYTHON

Output

[3]
[1, 2, 3]
[3, 3]

Built-in functions

Built-in functions are readily available for reuse.

We are already using functions which are pre-defined in Python

  • print()
  • int()
  • str()
  • len()

Finding Minimum

min()
returns the smallest item in a sequence or smallest of two or more arguments.

min(sequence)
min(arg1, arg2, arg3 ...)
PYTHON

Example - 1

Code

smallest= min(3,5,4)
print(smallest)
PYTHON

Output

3

Example - 2

Code

smallest = min([1,-2,4,2])
print(smallest)
PYTHON

Output

-2

Minimum of Strings

min(str_1, str_2)

Strings are compared character by character using unicode values.

  • P - 80(unicode)
  • J - 74(unicode)

Code

smallest = min("Python", "Java")
print(smallest)
PYTHON

Output

Java

Finding Maximum

max()
returns the largest item in a sequence or largest of two or more arguments.

max(sequence)
max(arg1, arg2, arg3 ...)
PYTHON

Example - 1

Code

largest = max(3,5,4)
print(largest)
PYTHON

Ouput

5

Example - 2

Code

largest = max([1,-2,4,2])
print(largest)
PYTHON

Output

4

Finding Sum

sum(sequence)
returns sum of items in a sequence.

Code

sum_of_numbers = sum([1,-2,4,2])
print(sum_of_numbers)
PYTHON

Output

5

Ordering List Items

sorted(sequence)
returns a new sequence with all the items in the given sequence ordered in increasing order.

Code

list_a = [3, 5, 2, 1, 4, 6]
list_x = sorted(list_a)
print(list_x)
PYTHON

Output

[1, 2, 3, 4, 5, 6]

Ordering List Items - Reverse

sorted(sequence, reverse=True)
returns a new sequence with all the items in the given sequence ordered in decreasing order.

Code

list_a = [3, 5, 2, 1, 4, 6]
list_x = sorted(list_a, reverse=True)
print(list_x)
PYTHON

Output

[6, 5, 4, 3, 2, 1]

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form