'how to print a list inside a function without using append method
k=[]
def subject(a):
for i in range(0,a):
ele=int(input("number: "))
k=ele
print(k)
n=int(input("Enter numb of elements: "))
subject(n)
#print(k)
I am not able to print whole list, that user input, please help?
Solution 1:[1]
Since you don't want to use append
, you should initialize your list with n
number of 0's
or None
. Try this:
def subject(a):
k = [0 for _ in range(a)] # Initialise your list with 'n' number of 0's
for i in range(0,a):
ele = int(input("number: "))
k[i] = ele # Filling the i'th index of list with user input
print(k)
n=int(input("Enter numb of elements: "))
subject(n)
#print(k)
Output:
Enter numb of elements:
3
number:
1
number:
2
number:
3
[1, 2, 3]
Solution 2:[2]
This would work just fine as well:
def subject(a):
k=[]
for i in range(a):
ele = int(input("number: "))
k += [ele]
print(k)
n = int(input("Enter numb of elements: "))
subject(n)
Solution 3:[3]
Alternate for append is by using "+" operand. However, I did with string
Try this too
def subject(a):
string=""
for i in range(a):
string+=input()
result=[int(x) for x in string]
return result
n=int(input("Enter a number :"))
print(subject(n))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | BeRT2me |
Solution 3 | Sankara Chelliah N |