Instruction like somelist = [1,2,3,4,5,6,7,8,9] creates a new list and
assigns it (the whole list) to your variable (somelist).
The second case, somelist = [x for x in somelist if x>4] is just filtering.
The for loop assigns each element from this list to a temporary variable x.
Then (inside this loop) if checks whether this (current) element meets
some condition, in your case, whether it is greater than 4.
Only if it is, this element is added to the new array, which finally will be
assigned to somelist.
And now what is the difference between plain assignment (just to somelist)
and the slice assignment ( to somelist[:]).
Imagine that initially there was otherList and you created your somelist
using plain assignment: somelist = otherList.
Actually, no second list has then been created, but somelist may be regarded as
another "pointer to" that first list.
In other words, both otherList and somelist point to the same internal
object (in this case, array).
Then, later in your code, if you used somelist[:] = ... you write new content
to the same internal object, so this new content is visible also using otherList
(e.g. in other part of your code).
But if you used plain assignment (somelist = ...), then:
- There is created a new internal object (array) and
somelist points
just to it.
- The old content is still visible as
otherList.
So as jonrsharpe pointed out, the decision which option to use depends
on what your application really needs.
In the simplest case, if you have no other variable pointing to the "old"
array, you can use plain assignment (IMHO a more natural option) and the
old array (now with no reference from any other variable) will be garbage
collected.