Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

Returning Multiple Values in Python

|| 0

Returning Multiple Values in Python
Stechies

There are many way to return multiple values using different ways in python.

Using Object

Example:

#  to return multiple object values 
class objTest: 
	def __init__(self): 
		self.str = "Rahu kalam falls every day"
		self.xy = 50

# This function returns an object of Test 
def fun(): 
	return objTest() 
	
# Driver code to test above method 
tst = fun() 
print(tst.str) 
print(tst.xy)


Output:

Rahu kalam falls every day
50

Using Tuple

In this function items are separated with a comma. It is created with or without (). These tuples are fixed, not changeable

Example:

# values from a method using tuple 
# This function returns a tuple 
def function(): 
	str = "india is religous country"
	str1 = "this just a fuction to show"
	return str, str1;

# Driver code to test above method 
str,str1 = function() 
print(str)
print(str1)


Output

india is religous country
this just a fuction to show

Using a list

It is created using square brackets. A list is like an array, but different from arrays as they contain different items type. It is mutable.

Example

#Using a list
def ftion(): 
	str = "Computer run on electricity "
	integerx = 101
	str1  = "this fucntion to show about the list"
	return str, integerx, str1; 

# Driver code to test above method 
list = ftion() 
print("from list method"), list

Output

from list method ('Computer run on electricity ', 101, 'this fucntion to show about the list')

Using a Dictionary

A Dictionary is similar to hash or map in other languages.

# This function returns a dictionary 
def ftion(): 
	dct = dict(); 
	dct['str'] = "hello world"
	dct['str1'] = "tau hello"
	dct['x'] = 55
	return dct 
# Driver code to test above method 
dct = ftion() 
print(dct)

Output

{'x': 55, 'str1': 'tau hello', 'str': 'hello world'}

Using a class

# A Python program to do return multiple 
# values from a method using class 
class Test: 
	def __init__(self): 
		self.st = "ishu and bible belongs to christinity "
		self.st1 = " this is xample of class to return multiple values"

# This function returns an object of Test 
def fun(): 
	return Test() 
	
# Driver code to test above method 
t = fun() 
print(t.st) 
print(t.st1)

Output

ishu and bible belongs to christinity 
 this is xample of class to return multiple values

 


Advertisement
Advertisement
Advertisement