Syntax question

Matteo Landi landimatte at gmail.com
Wed Jun 2 14:07:48 EDT 2010


Anyway I suggest you to use a syntax like:

>>>b = list(a)

in order to copy a list, it should be better than slicing.

On Wed, Jun 2, 2010 at 7:56 PM, geremy condra <debatem1 at gmail.com> wrote:
> On Wed, Jun 2, 2010 at 10:40 AM, pmz <przemek.zawada at gmail.com> wrote:
>> Dear Group,
>>
>> It's really rookie question, but I'm currently helping my wife in some
>> python-cases, where I'm non-python developer and some of syntax-diffs
>> make me a bit confused.
>>
>> Could anyone give some light on line, as following:
>> "ds = d[:]"  ### where 'd' is an array
>
> I'm guessing you mean that d is a list. The square
> braces with the colon is python's slicing notation,
> so if I say [1,2,3,4][0] I get a 1 back, and if I say
> [1,2,3,4][1:4] I get [2,3,4]. Python also allows a
> shorthand in slicing, which is that if the first index
> is not provided, then it assumes 0, and that if the
> second index is not provided, it assumes the end
> of the list. Thus, [1,2,3,4][:2] would give me [1,2]
> and [1,2,3,4][2:] would give me [3, 4]. Here, neither
> has been provided, so the slice simply takes the
> items in the list from beginning to end and returns
> them- [1,2,3,4][:] gives [1,2,3,4].
>
> The reason someone would want to do this is
> because lists are mutable data structures. If you
> fire up your terminal you can try the following
> example:
>
>>>> a = [1,2,3,4]
>>>> b = a
>>>> c = [:]
>>>> b[0] = 5
>>>> b
> [5,2,3,4]
>>>> # here's the issue
>>>> a
> [5,2,3,4]
>>>> # and the resolution
>>>> c
> [1,2,3,4]
>
> Hope this helps.
>
> Geremy Condra
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list