I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list.
Writing a + list
I get errors. The compiler handles a
as integer, thus I cannot use append, or extend either.
How would you do this?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Another way of doing the same,
None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.
l = ((pd.Series()).append(pd.Series())).tolist()
Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.
Lists are not optimized for modifications at the front, and
somelist.insert(0, something)
is an O(n) operation.somelist.pop(0)
anddel somelist[0]
are also O(n) operations.The correct data structure to use is a
deque
from thecollections
module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have anappendleft
method for insertions at the front.Demo:
New lists can be made by simply adding lists together.
How it works:
array.insert(index, value)
Insert an item at a given position. The first argument is the index of the element before which to insert, so
array.insert(0, x)
inserts at the front of the list, andarray.insert(len(array), x)
is equivalent toarray.append(x)
.Negative values are treated as being relative to the end of the array.