NoneType List

Thomas Passin list1 at tompassin.net
Sat Dec 31 12:07:25 EST 2022


Oops, my reply got lost somehow.  Here it is:

Everyone's answer to date has been too complicated.  What is going on is 
that list.append() changes the list in place.  It returns nothing.  If 
you want to append an item and then assign the result to a new list, you 
have to do just that:

l1.append(item)
# If we want a *copy* of the appended list:
l2 = l1[:]  # Changes to l2 will not change l1

# If we want another name for the appended list:
l2 = l1  # Changes to l2 will change l1 since they are the same object

list.sort() also operates in place.  There is a function sorted() that 
returns the sorted list (without changing the original list).

The same thing is true of set.add(). The set is changed in place, and 
nothing is returned.

On 12/31/2022 10:50 AM, Thomas Passin wrote:
> Happy New Year, everybody!
> I'm new in the Python List, new in Python world, and new in coding.
> A few days (weeks?) ago, I faced a problem trying to write a program for an
> exercise. I asked for help and nobody answered.
> In the meantime, I found a part of the solution, but a part still remains a
> mystery for me. Please run this small snippet, and help.
> Thanks
> 
> a = [1, 2]
> print()
> 
> print("a ==", a)
> print("type(a) is", type(a))
> 
> b = a.append(3)
> print("\nb =", "a.append(3)")
> print("b ==", b)
> print("type(b) is", type(b))
> 
> c = ['1', '2']
> print("\nc ==", c)
> print("type(c) is", type(c))
> 
> d = c.append('3')
> print("\nd =", "c.append('3')")
> print("d ==", d)
> print("type(d) is", type(d))
> 
> """
> I mean: why b = a.append(something) is the None type, and how to make a new
> list
> that contains all the items from a and some new items?
> I wasn't able to solve it in a few hours :(
> Now I know:
> """
> 
> crta = '='
> print('\n', 4 * ' ', crta * (len('The solution:')), sep='')
> print(3 * ' ', 'The solution:')
> print(4 * ' ', crta * (len('The solution:')), sep='')
> print('\nThe solution is the slice, an element of Python syntax that
> allows')
> print('to make a brand new copy of a list, or parts of a list.')
> print('The slice actually copies the list\'s contents, not the list\'s
> name:')
> 
> print()
> a = [1, 2]
> print("a ==", a)
> print("type(a) is", type(a))
> 
> b = a[:]
> print("\nb = a[:]")
> print("b ==", b)
> b.append(3)
> print("\nb =", "b.append(3)")
> print("b ==", b)
> print("type(b) is", type(b))
> print("\na ==", a)
> 
> print('But I still don't know why "b = a.append(something)" is the None
> type.')
> print('Is there anybody out there?!')



More information about the Python-list mailing list