The actual reason why you can't do either of the following,
l = [].append(2)
l = [2,3,4].append(1)
is because .append() always returns None as a function return value. .append() is meant to be done in place.
See here for docs on data structures. As a summary, if you want to initialise a value in a list do:
l = [2]
If you want to initialise an empty list to use within a function / operation do something like below:
l = []
for x in range(10):
value = a_function_or_operation()
l.append(value)
Finally, if you really want to do an evaluation like l = [2,3,4].append(), use the + operator like:
l1 = []+[2]
l2 = [2,3,4] + [2]
print l1, l2
>>> [2] [2, 3, 4, 2]
This is generally how you initialise lists.
Answer from Alexander McFarlane on Stack OverflowAppend to empty list in python - Stack Overflow
Append to an empty list using a single line for-loop python - Stack Overflow
Can I create an empty list, and at the same time append something to it?
Adding items to an empty list
my_list = []
my_list.append("dog")
my_list.append("cat")
# And so forthYou can add those to your list as your program runs instead of just printing them out.
More on reddit.comyour look will only iterate if there are items in the list, so just take the first if outside the loop to check if the list is empty or not
# Task 1a
# Create a function that places an element x in a sorted list
def insert_in_sorted(x, sorted_list):
if not sorted_list:
sorted_list.append(x)
return sorted_list
for i in range(len(sorted_list)):
if x > max(sorted_list) or not sorted_list:
sorted_list.append(x)
return sorted_list
elif sorted_list[i] > x:
sorted_list.insert(i, x)
return sorted_list
elif sorted_list[i - 1] and sorted_list[i + 1] == x:
sorted_list.insert(i, x)
return sorted_list
print(insert_in_sorted(2, []))
print(insert_in_sorted(5, [0, 1, 3, 4]))
print(insert_in_sorted(2, [0, 1, 2, 3, 4]))
print(insert_in_sorted(2, [2, 2]))
OUTPUT
[2]
[0, 1, 3, 4, 5]
[0, 1, 2, 2, 3, 4]
[2, 2, 2]
it seems you are doing left insert
import bisect
def insert_in_sorted (x, sorted_list):
bisect.insort_left(sorted_list,x)
return sorted_list
print(insert_in_sorted(2,[]))
print(insert_in_sorted(5,[0,1,3,4]))
print(insert_in_sorted(2,[0,1,2,3,4]))
print(insert_in_sorted(2,[2,2]))
[2]
[0, 1, 3, 4, 5]
[0, 1, 2, 2, 3, 4]
[2, 2, 2]
Write a proper comprehension, without append.
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(i for i in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Adding Explanation as to what happens, Append doesn't return anything,
y = []
x = [y.append(i) for i in range(10)]
print(x)
print(y)
produces
[None, None, None, None, None, None, None, None, None, None]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[Program finished]