Correct sequence of python functions [duplicate] - python

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 6 years ago.
I wrote a very basic python code, but it didn't work:
str = "asddasdvsatvsyvcstvcsacvsacvsaifteiopvnvbcshavsdsdzasbbnyju"
dict = {}
for i in str:
dict[i] = dict.get(i,0)+1
print(list(dict.items()).sort())
then I just changed the sequence of functions and separated them, and surprisingly it worked!
str = "asddasdvsatvsyvcstvcsacvsacvsaifteiopvnvbcshavsdsdzasbbnyju"
dict = {}
for i in str:
dict[i] = dict.get(i,0)+1
mylist = list(dict.items())
mylist.sort()
print(mylist)
What's happened from my first to second code that makes it work?

list.sort() sorts the list in place but returns None, that's why in the first example you're seeing None printed out.
You could use built-in sorted, that works exactly the same but creates and returns new list.

sort returns nothing. Therefore, print(l.sort()) prints nothing.
However, l.sort(), and therefore print(l.sort()), does sort the l
list.
Therefore, printing l after l.sort() has been executed will print something, namely, the l list sorted.

.sort() sorts the list in-place (it changes the list itself and doesn't make a copy). But it doesn't return anything (other than None).
If you do
print(list(dict.items()).sort())
You print the return value of sort() -- which is None.
But with
mylist.sort()
print(mylist)
You first sort, and then you print the value of mylist. That's what you want.
You could also have done
print(sorted(mylist))
But that leaves mylist unchanged.

Related

reverse list and append it to istelf [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 7 months ago.
Im trying to get a list to inputted in a function, and then the output would be the list, and then the reverse of the list added onto itself but for some reason whenever I reverse the variable reversal, it reverses list as well
def mirror(list):
reversel = list
reversel.reverse()
list.extend(reversel)
return list
test = ["alpha", "beta"]
print(mirror(test))
output
['beta', 'alpha', 'beta', 'alpha']
desired output
["alpha","beta","beta","alpha"]
You can use slicing:
def mirror(lst):
return lst + lst[::-1]
test = ["alpha", "beta"]
print(mirror(test)) # ['alpha', 'beta', 'beta', 'alpha']
An issue in the provided code is that (i) reversel = list (but don't use list as a name) does not copy the object, and (ii) reverse() reverses the list in place. These two lines of code, therefore, reverse the list list (as well as reversel). As a result, now list and reversel both are ["beta", "alpha"]. Then after list.extend(reversel), list becomes what you observe.
Also, there is another subtle issue; it is not generally recommended doing both of the following: (i) modify a given object, and (ii) return the object; this might cause confusion (I believe). It is better to do only one of them; modify an object in place (like reverse), or don't modify the object but return a modified copy of the object (like reversed).
Here is a solution without using reverse().
def mirror(list_to_mirror):
reversel = list_to_mirror
reversel = reversel[::-1]
#This is an equivilant to reverse()
list_to_mirror.extend(reversel)
return list_to_mirror
if __name__ == "__main__":
test = ["alpha", "beta"]
print(mirror(test))
This should work -
def mirror(list):
reversel = [i for i in list]
reversel.reverse()
list.extend(reversel)
return list
test = ["alpha", "beta"]
print(mirror(test))
when using '=' it stores the location of the variable. So when using a function like reverse, both values change.
A way that doesn't require creating and discarding a copy:
def mirror(lst):
lst += reversed(lst)
return lst

Why does the print statement give output as None instead of sorted list? [duplicate]

This question already has answers here:
Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list?
(6 answers)
Closed 4 years ago.
import random
L = []
for i in range(0, 10):
L.append(random.randrange(1, 10))
print(L.sort())
Output:None
list.sort sorts the list in-place and returns None. You either want to do:
L.sort()
print(L)
or use the sorted function.
list.sort mutates the list instead of returning it.
You can use the sorted() function instead:
print(sorted(L))

Why does newList = list.remove(x) return None? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 7 years ago.
I have a list below and I want to remove a value and set it to a new variable. Why does it return None?
aList=[1,2,3,4,5]
newList = aList.remove(1)
print(newList)
#prints None
but when I do it this way, it works exactly as I would expect.
aList=[1,2,3,4,5]
aList.remove(1)
newList = aList
print(newList)
#prints [2,3,4,5]
In Python, when a function mutates an object it generally returns None.Otherwise it returns the new object.
remove mutates the original object, which is why when you do aList.remove(1) and then print the list, you will see that the list is different.

Get the length of reversed list [duplicate]

This question already has answers here:
Why does len() not support iterators?
(2 answers)
Closed 7 months ago.
Getting the length of reversed list doesn't work:
lst = [1,2,3]
lst = reversed(lst)
print len(lst)
throws TypeError: object of type 'listreverseiterator' has no len()
A work around is:
lst = [1,2,3]
lst_length = len(lst)
lst = reversed(lst)
print lst_length
# OR
lst = lst[::-1]
print len(lst)
Now my real question is why?
Simply reversing a list does not alter the length of the list,
so why is Python throwing that exception?
The function reversed() returns an iterator, not an actual list.
You cannot directly get the len() of an iterator (see here).
You could instead reverse the list using Extended Slice syntax:
lst_reversed = lst[::-1]
or reverse the list in place:
lst.reverse()
If you must use an iterator you could first turn it into a list:
lst_reversed = list(reversed(lst))
With each of these approaches len() will then work as expected.
reversed doesn't produce new list, it just return iterator object. You can use lst.reverse() - and it doesn't return anything, but make your lst in reversed order
reversed returns iterator so to determine length you have to consume it.
For example rev_len = len(list(reversed(lst))).
FYI list.reverse method reverses a list in place: lst.reverse()
Anyway your reversed list has the same size as the original one, so you can just determine the length even before reversing.

Why can't I sort a list right after I make it? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 9 years ago.
I have a set I want to make into a sorted list. I run:
sorted_list=list(my_set).sort()
but this returns none, even when both list(my_set) and my_set are both nonempty. On the other hand this:
sorted_list=list(my_set)
sorted_list.sort()
works just fine.
Why is this happening? Does python not allow methods to be called on objects directly returned by constructors?
.sort() sorts the list in place and returns None. You need to use the sorted() function here.
>>> a = [3, 2, 1]
>>> print a.sort()
None
>>> a
[1, 2, 3]
>>> sorted(a)
[1, 2, 3]
It's simple:
sort() makes sorting in place and returns None
sorted() returns a sorted copy
Here's a quote from How To/Sorting - Python Wiki:
Python lists have a built-in sort() method that modifies the list
in-place and a sorted() built-in function that builds a new sorted
list from an iterable.
You're looking for this:
sorted_list = sorted(list(my_set))
Or even simpler:
sorted_list = sorted(my_set)
sort() sorts the list in place and returns None, and that's what will be stored in sorted_list. That's not what we expected.
On the other hand, sorted() returns a new sorted list with the elements it received as a parameter (it can be a list or a set: in fact, any iterable), and that's what gets assigned to sorted_list - just what we wanted!
Because the sort method changes the list in-place. What do you want is the sorted function, which returns a sorted list:
sorted_list = sorted(my_set)
The sorted() function does not touch its argument, since it makes a copy of it. On the other hand, the sort method directly changes the original list and returns None.

Categories

Resources