Function Return with updated values [duplicate] - python

This question already has answers here:
What is the difference between `sorted(list)` vs `list.sort()`?
(7 answers)
Closed 4 years ago.
I was trying to sort list elements inside a function without return when I try to print the list by its name it does not get sorted, but it is sorted inside a function.
I have to update the list inside the function without returning
def sort(n):
n.append(10)
sorted(n)
n = [5,1,2,3]
print(n)
Expected : [1,2,3,5]
actual: [5,1,2,3]

I'm sorry, I made a series of mistakes myself. It's a lesson for me too.
def isort(n):
n.append(10)
n.sort() #I used n[:] = sorted(n), but it's superfluous.
n = [5,1,2,3]
isort(n)
print(n)
m = [7,9,3,13]
isort(m)
print(m)
output:
[1, 2, 3, 5, 10]
[3, 7, 9, 10, 13]
sort is an existed fuction in python, need to change it to other name. I changed to isort.
We have to call the function isort to let it do its work.
We need to update the elements in the list to make the list update. [:] Slice notation here.
It's better to use different name between function argument and the call. (n and m here).
Many thanks to DYZ, Primusa, and Tomothy32 :)

Related

Why the "NONE" is getting appended in list? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
I have made 2 functions: one to generate random values from 0 to 20, and another to check if the value generated by function random matches the value of list. If the value matches then random should start again to produce new value
My code is:
import random
mylist=[6,2,4]
y=int()
def randoom():
str=random.randint(0,20)
return str
def checklist():
y=randoom()
print(y,"Generated value y")
if y in mylist:
print(y,"already exist in list")
checklist()
if y not in mylist:
return y
for b in range(1,10):
x=checklist()
print(x," X got the value")
mylist.append(x)
print(mylist)
My output is: [6, 2, 4, 5, 12, 7, 16, 13, None, 17, 19, None]
Why is None getting appended?
I tried everything in last 3 days to figure out why None is getting appended in list even when I made sure the function runs again to produce a new value of y if it matches the list.
Your checklist function can return None if y is in mylist:
if y in mylist:
print(y,"already exist in list")
checklist() # Executes checklist again, but discards the return value
There is no path after this that can return a value, so the function returns None. You can fix this by returning checklist():
if y in mylist:
print(y,"already exist in list")
return checklist() # Executes checklist again, but returns the value
The return value of checklist is not being saved in your variable after being executed. Fixing this should make your Code work.
Still, you have at the very top of your program a variable named str. Since str is also a function in python, this could cause issues down the road. I would recommend to change this.

Python Reversing List Using Slicing [duplicate]

This question already has answers here:
Python reverse-stride slicing
(8 answers)
Closed 3 years ago.
I am trying to create a function that reverses and mutates a list via slicing/appending without using [::-1] or .reverse(). I am looking for any additional resources online but it seems to be the only two popular reserving techniques.
Can anyone help me think of how I can write this?
I would try:
n = len(a)
for i in range(n):
a.append(a[n - (i+1)])
a = a[n:]
This is one way you can do it:
a = [1, 2, 3, 4]
b = [0]*len(a)
for i in range(len(a)):
b[len(a) - 1 - i] = a[i]
print(b)

Python recursive function to obtain next item on a list [duplicate]

This question already has answers here:
Basics of recursion in Python
(5 answers)
Closed 4 years ago.
I'm quite new to recursion and I have to solve a problem for my homeworks which asks to define a recursive function to get the next element on a given item of a list.
I made the iterative version but I don't understand how to write the recursive one.
def next_value(lst,v):
ind = lst.index(v)
list1_result = lst[ind+1]
return list1_result
a = [4, 2, 10, 3, 2, 5]
print(next_value(a,10))
# output: 3
Your solution seems okay but if it absolutely has to be recursive, here's an example implementation:
def next_value(lst, v):
if (len(lst) < 2):
return None
if (lst[0] == v):
return lst[1]
return next_value(lst[1:], v)
Basically we pass slices from the same list until we find an element with the given value. If the length is less than 2, the list is either empty or we have looked through it all. In that case we return None to denote that there is no valid answer.

Iterating - Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 5 years ago.
Trying to remove negative numbers from a list. I kept running into an issue where two successive negative numbers did not get removed. My code is quite simple:
numbers = [-5, 1, -3, -1]
def remove_neg(num_list):
for item in num_list:
if item < 0:
num_list.remove(item)
print(remove_neg(numbers))
#[1, -1]
I found the answer online after trying 4 different versions of my code and pulling a few hairs out of my head. The answer I found assigned r = numbers[:] and then removed items from r instead of the initial list.
def remove_neg(num_list):
r = numbers [:]
for item in num_list:
if item < 0:
r.remove(item)
print(r)
I understand this concept to have two list variables point to separate data. What I don't understand, is why my initial code doesn't work. Shouldn't for i in numbers: iterate through every item in the list? Why would two successive numbers not be treated the same? I've scoured looking for why and can't seem to find an answer.
In the first example you're modifying the list while iterating over it, which, as you've seen, messes up the iteration. While the second example works, it's very inefficient, and it would be much easier to use a list comprehension to construct a new list without the negatives:
def remove_neg(num_list):
return [x for x in num_list if x > 0]

Python shuffle list not working [duplicate]

This question already has answers here:
Shuffling a list of objects
(25 answers)
Closed 8 years ago.
I am new with python. coming from a C++ background I'm ironically having trouble understanding the simplicity of this language not to mention how IDLE works.
anyhow I need to write a simple function that takes a list and returns a new list with the elements inside it shuffled
this is what I have so far
import random
def shuffle():
aList = []
i = 0
for i in range(0, 5):
elements = input(": ")
aList.append(elements)
shuffleList = random.shuffle(aList)
return shuffleList
shuffle()
and after I enter the elements(numerical numbers in this case), nothing outputs.. So the shuffleList for some reason is not being shown in there. Any ideas ?
>>>
: 1
: 2
: 3
: 4
: 5
>>>
random.shuffle shuffles the list in place, and its output is None.
Since you store and return its output in shuffleList = random.shuffle(aList), nothing is printed.
So instead, return the aList back:
import random
def shuffle():
aList = []
i = 0
for i in range(0, 5):
elements = input(": ")
aList.append(elements)
random.shuffle(aList)
return aList
random.shuffle is an in-place operation, it does not return anything
>>> l
[0, 1, 2, 3, 4]
>>> random.shuffle(l)
>>> l
[0, 3, 1, 4, 2]
Shuffle shuffles the list, it doesn't return a new list. Try this:
import random
def shuffle():
aList = []
for i in range(0, 5):
elements = input(": ")
aList.append(elements)
random.shuffle(aList)
return aList
print shuffle()
random.shuffle works in place, meaning it updates the provided parameter, rather than returning a value (other than the default, None). In C++, you would need to pass a reference to the list instead (e.g. int** aList), but in Python this distinction doesn't really exist.
So, you're actually setting shuffleList to None, and then returning it!
You can confirm this by using print to actually show the results when you're finished - just returning the value from the function won't output anything, as far as I am aware:
results = shuffle()
print results
To fix it, just return aList, instead of storing the result in another variable:
random.shuffle(aList)
return aList
random.shuffle() reorders the list in-place and returns None.

Categories

Resources