Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [:] do?

Tags:

python

return self.var[:]

What will that return?

like image 367
Richard Knop Avatar asked Nov 15 '10 22:11

Richard Knop


People also ask

What does [:] in Python do?

It is a slice from the beginning of the sequence to the end, usually producing a shallow copy.

What does IMG [: ::- 1 mean?

The : means "take everything in this dimension" and the ::-1 means "take everything in this dimension but backwards." Your matrix has three dimensions: height, width and color. Here you're flipping the color from BGR to RGB.

What does * list mean in Python?

Python List also includes the * operator, which allows you to create a new list with the elements repeated the specified number of times. The following program repeats the list the given number of times using the * operator −

What does [] mean in Python?

Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.


2 Answers

Python permits you to "slice" various container types; this is a shorthand notation for taking some subcollection of an ordered collection. For instance, if you have a list

foo = [1,2,3,4,5]

and you want the second, third, and fourth elements, you can do:

foo[1:4]

If you omit one of the numbers in the slice, it defaults to the start of the list. So for instance

foo[1:] == [2,3,4,5]
foo[:4] == [1,2,3,4]

Naturally, if you omit both numbers in the slice you will get the entire list back! However, you will get a copy of the list instead of the original; in fact, this is the standard notation for copying a list. Note the difference:

>>> a = [1,2,3,4]
>>> b = a
>>> b.append(5)
>>> a
[1, 2, 3, 4, 5]
>>>
>>> a = [1,2,3,4]
>>> b = a[:]
>>> b.append(5)
>>> a
[1, 2, 3, 4]

This occurs because b = a tells b to point to the same object as a, so appending to b is the same as appending to a. Copying the list a avoids this. Notice that this only runs one level of indirection deep -- if a contained a list, say, and you appended to that list in b, you would still change a.

By the way, there is an optional third argument to the slice, which is a step parameter -- it lets you move through the list in jumps of greater than 1. So you could write range(100)[0::2] for all the even numbers up to 100.

like image 63
Katriel Avatar answered Sep 20 '22 06:09

Katriel


If self.var is a mutable sequence, it will return a shallow copy of that sequence.

If self.var is an immutable built-in sequence such as a string or a tuple, most implementations will return self.var itself.

like image 34
Frédéric Hamidi Avatar answered Sep 24 '22 06:09

Frédéric Hamidi