Differencebetween List and List[:] in Python

What is the difference between list and list[:] in python?

When reading, list is a reference to the original list, and list[:] shallow-copies the list.

When assigning, list (re)binds the name and list[:] slice-assigns, replacing what was previously in the list.

Also, don't use list as a name since it shadows the built-in.

Get difference between two lists

To get elements which are in temp1 but not in temp2 :

In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']

Beware that it is asymmetric :

In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])

where you might expect/want it to equal set([1, 3]). If you do want set([1, 3]) as your answer, you can use set([1, 2]).symmetric_difference(set([2, 3])).

Difference between list() and [ ] in Python 3

Since list() is a function that returns a list object and [] is the list object itself, the second form is faster since it doesn't involve the function call:

> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop

> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop

So if you really want to find a difference, there's that. In practical terms they're the same, however.

What's the difference between list[::] and list?

In Python, all assignments bind a reference to a name. Operators call a method of an existing reference1. In your case, the statement

matrix = ...

is purely an assignment2. It computes the right hand side, and binds it to the name matrix in the local function scope. Whatever object matrix referred to when you passed it in remains untouched.

This is why you don't see the changes you made. It's not that the function doesn't work this way, it's that it doesn't do anything with the rotated list. The data is discarded as soon as the function exits.

The operation

matrix[:] = ...

on the other hand is not an assignment in the semantic sense, despite the = symbol3. It's a call to matrix.__setitem__(...)4. The__setitem__ method, like any other method, operates directly on the object without changing it's name bindings.

As far as indexing goes, [:] is equivalent to [::]. They are shorthand for [0:len(matrix)] and [0:len(matrix):1], respectively. In both cases, the default step size will be used. In general, any index with colons in it will be converted to a slice object. Missing elements are set to None and replaced by the sequence-specific defaults shown here.


1 Some operators, like += perform an assignment after calling a method. These are called augmented assignments. But that's not a case we're interested in right now.

2 Besides literal assignment statements (=), some other types of assignments are def (which binds a function object to its name), class (which does the same for a class object), import (which binds a module or element of a module to a name), passing arguments to a function (which binds objects to the local argument names or kwarg dictionary keys), and for (which binds an element from an iterator to the loop variable at each iteration).

3 It's still an assignment from the point of view of the parser, but the statement is handled completely differently. A similar statement that is not actually an assignment is using the = operator on an attribute implemented as a descriptor, such as a property.

4 Technically, it's more of an equivalent to type(matrix).__setitem__(matrix, ...), but with some additional optimizations. For example, the metaclass of type(matrix) won't ever be searched.

What's the difference between list() and []

One's a function call, and one's a literal:

>>> import dis
>>> def f1(): return list()
...
>>> def f2(): return []
...
>>> dis.dis(f1)
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>> dis.dis(f2)
1 0 BUILD_LIST 0
3 RETURN_VALUE

Use the second form. It's more Pythonic, and it's probably faster (since it doesn't involve loading and calling a separate funciton).

Static typing in python3: list vs List

Not all lists are the same from a typing perspective. The program

def f(some_list: list):
return [i+2 for i in some_list]

f(['a', 'b', 'c'])

won't fail a static type checker, even though it won't run. By contrast, you can specify the contents of the list using the abstract types from typing

def f(some_list: List[int]) -> List[int]:
return [i+2 for i in some_list]

f(['a', 'b', 'c'])

will fail, as it should.

Difference between list = [] vs. list.clear()

Calling clear removes all the element from the list. Assigning [] just replaces that variable with another empty list. This becomes evident when you have two variables pointing to the same list.

Consider the following snippet:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]

As compared to this one:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]

How Do You Tell The Difference Between List and List Of Lists

Check the type of the first element:

isinstance(the_list[0], list)

i.e:

>>> isinstance(list_1[0], list)
False
>>> isinstance(list_2[0], list)
True

However, what do you mean by a list of lists? Is the following a list of lists?

[1, [1, 2, 3], 1, 1]

If so, then you can check if any of the elements are lists:

any(isinstance(l) for l in the_list)

What about the case when they are all list? Is the following the only true "list of lists"?

[[1, 2], [1, 2]]

If so, then you can check if all the elements are lists:

all(isinstance(l) for l in the_list)

However, although these questions are important, for your example, the first snippet will suffice.

Difference between list.pop() and list = list[:-1]

Yes. pop is O(1) and mutates the original list, while slice is O(n) and creates a copy of the list. Less formally, the pop method is an operation on the element at the end of the list and is defined in CPython as a call to list_resize(self, Py_SIZE(self) - 1);. This doesn't traverse the entire structure.

On the other hand, list_slice allocates a new list and loops over the entries in the old list ranging from the beginning to the end - 1, copying references to each item to the new list.

If what you're trying to do is remove the last element of the list, use pop or del a[-1].



Related Topics



Leave a reply



Submit