Python List concepts [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 7 years ago.
I am new to python programming
why this assignment value to k is giving 'None' value
> >>> l=[2,3,4]
> >>> k=l.append(14)
> >>> print k
None
> >>> print l
[2, 3, 4, 14]
in above example List,I append the 14 value to list and then assigned to k but k is printing None please tell me the reason why its printing None instead of appended list?
Thanks
mukthyar

append changes the current list and doesn't return anything. Use:
k = l + [14]
or
k = l[:] # Copy list
k.append(14)

Most methods in Python which mutate their instance (.append(), .sort(), et al.) do not return a copy of the object. Thus l.append(X) does actually return "None" just as l.sort() would.
You'd probably want to use something more like:
l.append(14)
k = l[-1]

In python default return type is None so if your function is not return any value then you will get the None from that function. There are different functions for the object. Some functions are perform on same object and others are return the modified copy. For example list.sort will change the original list while sorted will return the new sorted list without changing the original one. So append is working on object so it will change the object value instead of returning new modified copy.
Hope this will make your view clear about append method.

What you are seeing is expected - the list.append method does not return the modified list. If you take a look at the relevant section of the Python tutorial, you'll notice that methods which return useful values are documented as such.
Working in the interactive interpreter, you can tell that the expression yields None by the lack of output:
>>> l = [1, 2, 3]
>>> l.append(14)
>>>
If (theoretically) list.append returned the list, you would see the following instead:
>>> l = [1, 2, 3]
>>> l.append(14)
[1, 2, 3, 14]
>>>
Using the interactive interpreter this way can save you from printing every value.

from python document
list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
in simple word append function returns nothing but None
suggested reading

Related

Python - Why doesn't the reverse function doesn't work when given with list but does work with the variable? [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 12 months ago.
Beginner question...
Why does this happen? Why doesn't the reverse function work when given with list but does work with the variable?
>>> a=[1,2].reverse()
>>> a <--- a is None
>>> a=[1,2]
>>> a.reverse()
>>> a <--- a is not None and doing what I wanted him to do
[2, 1]
>>>
It does work. The list reverse method in Python doesn't return reversed list (it doesn't return anything == returns None), it reverses the list it's applied to in place. When you call it on a list literal it is in fact reversed, but there is no way to get the reversed list.
There is reversed function (https://docs.python.org/3/library/functions.html#reversed) that does what you expect
reverse() doesnt return any value,i.e, it returns None.
Reverse() modifies the list in place.
In your first case, you are inturn setting a = None.
In your second case, a is modified by reverse(), and you are able to print the modified "a".
That is because reverse() returns None, but it reverses the order of items in the list.
For example,
>>>a = [1, 2].reverse() # It reversed [1, 2] to [2, 1] but returns None.
>>>a # The reversed value of [2, 1] disappears,
# And returned value of None has been assigned to variable a
None
>>>a=[1,2]
>>>a.reverse() # The order of items of a has been reversed and return None,
# but there is no variable to take returned value, None.
>>> a
[2, 1]

Why can't a list be constructed and modified in the same line?

For example, why is a not equal to b?
a = [1]
a.append(2)
print(a) # [1, 2]
b = [1].append(2)
print(b) # None
The syntax for b doesn't look wrong to me, but it is. I want to write one-liners to define a list (e.g. using a generator expression) and then append elements, but all I get is None.
It's because:
append, extend, sort and more list function are all "in-place".
What does "in-place" mean? it means it modifies the original variable directly, some things you would need:
l = sorted(l)
To modify the list, but append already does that, so:
l.append(3)
Will modify l already, don't need:
l = l.append(3)
If you do:
l = [1].append(2)
Yes it will modify the list of [1], but it would be lost in memory somewhere inaccessible, whereas l will become None as we discovered above.
To make it not "in-place", without using append either do:
l = l + [2]
Or:
l = [*l, 2]
The one-liner for b does these steps:
Defines a list [1]
Appends 2 to the list in-place
Append has no return, so b = None
The same is true for all list methods that alter the list in-place without a return. These are all None:
c = [1].extend([2])
d = [2, 1].sort()
e = [1].insert(1, 2)
...
If you wanted a one-liner that is similar to your define and extend, you could do
c2 = [1, *[2]]
which you could use to combine two generator expressions.
All built-in methods under class 'List' in Python are just modifying the list 'in situ'. They only change the original list and return nothing.
The advantage is, you don't need to pass the object to the original variable every time you modify it. Meanwhile, you can't accumulatively call its methods in one line of code such as what is used in Javascript. Because Javascript always turns its objects into DOM, but Python not.

Reverse list in array Python using append remove method without build in function [duplicate]

This question already has answers here:
Modifying a list while iterating when programming with python [duplicate]
(5 answers)
Closed 4 years ago.
I am trying to reverse a list using append and remove method. But there is a problem in my method of doing this solution. Perhaps anyone give me a better explanation
list_in_order = [1,2,3,4,5,6]
def reverse(list):
r=[]
for i in list:
print (i)
r.append(i)
list_in_order.remove(i)
return r
print(reverse(list_in_order))
You can't use list.append, as that appends to the end of the list. What you want is to append to the start of the list. For that use list.insert. For more details see the list docs.
list_in_order = [1,2,3,4,5,6]
def reverse(L):
r = []
for i in L:
r.insert(0, i)
return r
print(reverse(list_in_order))
The other option is of course to use slice notation.
>>> [1,2,3,4,5,6][::-1]
[6, 5, 4, 3, 2, 1]
To make some constructive criticisms of the code in your question
Don't refer to variables outside of the function, unless you really intend to use globals. list_in_order.remove(i) refers to your global variable, not your function argument (although they ultimately refer to the same thing in this case). It may have been a typo but its worth pointing out that it's not quite right.
Don't use variable names that hide built in types. list, dict, tuple, set etc... These are not good names for variables as they will hide those types from further use in the scope that variable exists in and it may be difficult to find the source of the errors you get as a result.
Make your functions do one of two things; either modify the input (called in place modification) and return None or create a new collection and return that.
Don't iterate over a collection while modifying it. See linked dupe for elaboration.
In [11]: list_in_order = [1,2,3,4,5,6]
In [12]: list(reversed(list_in_order))
Out[12]: [6, 5, 4, 3, 2, 1]
Do you want [6, 5, 4, 3, 2, 1] for the result?
If so, just use list_in_order[::-1]
If you must use the append and remove,
list_in_order = [1,2,3,4,5,6]
def reverse_list(target_list):
copied_list = target_list.copy()
r=[]
for i in reversed(target_list):
r.append(i)
copied_list.remove(i)
return r
don't remove list elements when it in loop.
don't use 'list' for variable/parameter name.
I would make it like this :
list_in_order = [1,2,3,4,5,6]
def reverse(list):
counter = len(list)
for i in range(0,counter/2):
print(i)
list[i],list[counter-i] = list[counter-i], list[i]
return list
print(reverse(list_in_order))
This is a one way to do it, but you can do it using a recursion :)

When I run this code, it gives None instead of the 'Python' getting appended to the List. Why is that so? [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 5 years ago.
When I run this code, it gives None instead of the 'Python' getting appended to the List. Why is that so?
input_tuple = ('Monty Python', 'British', 1969)
input_list = list(input_tuple)
print(input_list)
input_list_1 = input_list.append('Python')
print(input_list_1)
This is the offending line:
input_list_1 = input_list.append('Python')
The append() method updates the list in place. It returns no value (i.e. it returns None). Since you are assigning the return value of append() to input_list_1, the printed value is expected to be "None".
array.append() changes the array passed directly instead of returning the changed array. To give an example:
array = [1, 2, 3]
array.append(4)
print(array)
Outputs [1, 2, 3, 4]. Therefore, your code should be:
input_tuple = ('Monty Python', 'British', 1969)
input_list = list(input_tuple)
print(input_list)
input_list.append('Python')
print(input_list)
input_list_1 returns None because you are appending into input_list. At this point input_list_1 stores returned value of append operation - which is None. To print updated list you should print the input_list.
input_list is list object and append is a list object method which is direct changes in list instant of return changes.that's why none object is returned and input_list_1 does not print anything.

list.append() in python returning null [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 6 years ago.
What is the actual difference between list1.append() and list1+list2 in python??
Along with this, why the following statement return NULL?
print(list1.append(list2))
{where list1 and list2 are 2 simple list}
list.append() modifies the object and returns None.
[] + [] creates and "returns" new list.
https://docs.python.org/2.7/tutorial/datastructures.html#more-on-lists
Recommended reading: http://docs.python-guide.org/en/latest/writing/gotchas/
Returning None is a way to communicate that an operation is side-effecting -- that is, that it's changing one of its operands, as opposed to leaving them unchanged and returning a new value.
list1.append(list2)
...changes list1, making it a member of this category.
Compare the following two chunks of code:
# in this case, it's obvious that list1 was changed
list1.append(list2)
print list1
...and:
# in this case, you as a reader don't know if list1 was changed,
# unless you already know the semantics of list.append.
print list1.append(list2)
Forbidding the latter (by making it useless) thus enhances the readability of the language.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.append(b) # append just appends the variable to the next index and returns None
>>> print a
[1,2,3,[4,5,6]]
>>> a.extend(b) # Extend takes a list as input and extends the main list
[1,2,3,4,5,6]
>>> a+b # + is exactly same as extend
[1,2,3,4,5,6]
When you print a function, you print what it returns and the append method does not return anything. However your list now has a new element. You can print the list to see the changes made.
list1 + list2 means that you combine 2 lists into one big list.
list1.append(element) adds one element to the end of the list.
Here's an example of append vs +
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>>
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]

Categories