Appending item to list within a list comprehension using if/else and for loop
Firstly, you can simplify (x==y) | (x==z)
to x in (y, z)
. Also it's recommended to use logical or
instead of bitwise OR |
in logical expressions, but that's beside the point.
To answer your question, yes, you just have the syntax a bit confused. Putting if
in the expression part of the comprehension makes a ternary. The equivalent in the for
loop would be:
for i in range(movies.shape[1]):
column.append(movies.columns[i] if movies.dtypes[i] in (float, int) else 0)
The way to use an if
as a filter is to put it at the end of the comprehension:
column = [movies.columns[i] for i in range(movies.shape[1]) if movies.dtypes[i] in (float, int)]
The syntax for a comprehension is described in the documentation here: Displays for lists, sets and dictionaries. A ternary is called a conditional expression in the Python docs.
Append to list if not None, within a list comprehension
You can use if condition in list comprehension
[int(value) for value in tmp['frames'] if value is not None]
Appending to a list comprehension in Python returns None
append
only works on variables, not list literals, since it updates the list object itself and does not return the resulting list.
As @Tomalak mentioned noted, running a similar operation on a simple list also returns None
>>> [1, 2, 3].append(4) == None
True
Appending an element in nested list comprehension python
No need to over-complicate things.
>>> list1 = [1,2,3]
>>> list2 = ['a','b','c']
>>> [list2 + [x] for x in list1]
[['a', 'b', 'c', 1], ['a', 'b', 'c', 2], ['a', 'b', 'c', 3]]
How to append lists using list comprehension to an exsiting list
You can use .extend()
instead of .append()
:
source = [1, 2, 3, 4, 5]
target = []
target.extend([r] for r in source if r == 2 or r == 4)
print(target)
# [[2], [4]]
It's possible to use .extend()
in this case because it receives an iterable as an argument.
List comprehension with append in one line
append
changes the list you call it on. It doesn’t produce a new list, so it returns None
to avoid confusion.
Python 3.6+, using a splat (expands an iterable) in a list literal:
a = [*machine, "All"]
previously, list concatenation with the +
operator:
a = list(machine) + ["All"]
Altering a list using append during a list comprehension
or
may be lazy, but list definitions aren't. For each o
in x
, when the [o,x.append(o) or 0][type(o)==type([])]
monstrosity is evaluated, Python has to evaluate [o,x.append(o) or 0]
, which means evaluating x.append(o) or 0
, which means that o
will be appended to x
regardless of whether it's a list. Thus, you end up with every element of x
appended to x
, and then they get appended again and again and again and OutOfMemoryError
List comprehension to add item to every list in a list of lists
Because insert
is inplace (it modifies the list it is called upon and returns None
).
You could do [[i.insert(0, 'x')] for i in ls]
(without re-assigning it to ls
) but the explicit loop has better readability and no "magic" side effects.
ls = [[1,2,3],[4,5,6],[7,8,9]]
[[i.insert(0, 'x')] for i in ls]
print(ls)
>> [['x', 1, 2, 3], ['x', 4, 5, 6], ['x', 7, 8, 9]]
Do Python list comprehensions append at each iteration?
Appending to a list is amortized O(1)
and not O(k)
; lists are implemented as variable-length arrays, not as linked-lists. The complexity applies both for for
loops with my_list.append
calls and list-comprehensions (which, spoiler alert, also append).
So in both cases. The complexity is O(N)
.
List-comprehensions generally perform better because they are specialized to do one thing: create lists. The byte-code produced for them is specific to that. (See the LIST_APPEND
bytecode)
Also note that list-comprehensions, like for-loops, don't necessarily append at each iteration. Using if
clauses to filter out elements of the iterable you're looping through is commonly used.
If you'd like to see how list-comprehensions are implemented in CPython, you can take a look at the bytecode produced for them and scan through ceval.c
for the actions performed for each.
The byte-code can be seen with dis
after we compile a list-comprehension expression:
dis(compile('[i for i in range(10)]', '', 'exec').co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
Then, scan through the cases in ceval.c
or look at their documentation in the dis
module.
Related Topics
Stopping a Thread After a Certain Amount of Time
Having Trouble Making a List of Lists of a Designated Size
What Is Different Between All These Opencv Python Interfaces
How to Take the Nth Digit of a Number in Python
Python Regular Expression Re.Match, Why This Code Does Not Work
Why Does Python's _Import_ Require Fromlist
Overloaded Functions in Python
How to Stop Numpy from Multithreading
Pandas Groupby Without Turning Grouped by Column into Index
How to Copy Over an Excel Sheet to Another Workbook in Python
Can One Get Hierarchical Graphs from Networkx with Python 3
How to Write Tests for the Argparse Portion of a Python Module
Inserting a Table Name into a Query Gives SQLite3.Operationalerror: Near "": Syntax Error
Why Is Exponentiation Applied Right to Left
How to Import Data from Mongodb to Pandas
Unicodedecodeerror: 'Ascii' Codec Can't Decode Byte 0Xe2 in Position 13: Ordinal Not in Range(128)