[Tutor] yet another misunderstanding on my part
Alan Gauld
alan.gauld at btinternet.com
Thu Oct 23 13:17:51 CEST 2014
On 22/10/14 19:48, Clayton Kirkwood wrote:
> Regarding the index out of range, I know what it meant, I was just kind of
> surprised that Python didn't automatically create the node and stuff a value
> in.
But what should Python do in this case
aNewList[1000000] = 42
Should Python create a 1 million element list with only one value?
That would be a slow operation. What should the other values be
set to? None, presumably?
> !description.append() = something
> !
> !
> !from. There's nothing in Python that I've ever seen that suggests that
> !would work, and the error message should be clear:
>>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>>> [weapon.strip() for weapon in freshfruit]
> ['banana', 'loganberry', 'passion fruit']
> From 5.1.3 in the Python3 tutorial.
> Although not an = assignment, some value
> is being stored in weapon after being strip of whitespace.
> I realize they are different, maybe just not sure how different:<)
This is a list comprehension with a very specific syntax.
It is equivalent to
aList = []
for weapon in freshfruit:
aList.append(weapon.strip())
It is very different from assigning a value to a function call.
> In this case, somehow
> Python seems to keep track of the location so that the modified
> value(dropping spaces) replaces the original location.
No it does not replace the original location it is appended
to the list.
> So two questions remain. Why can't codes.append(code) just replace the code
> in the previous line and descriptions.append(description) replace the
> description in the previous line.
Because the append() adds it at the end it doesn't replace anything.
> value.strip() = some value . Second question, why can't a numeric index be
> used to make assignment to a specific location like a[1] = "some value"?
It can if that entry already exists.
listA = [0,1,2,3,4,5] #initialize with elements
listA[3] = 9
print(listA) # -> [0,1,2,9,4,5]
listB = []
listB[3] = 9 # error because listB has no elements yet.
listB += [0,1,2,3,4] # add some elements
listB[3] = 9 # OK now.
> It is clear that once the array is created,
Its not an array, its a list. Most specifically it is not a C style
block of memory that is just filled in with a set of bytes. It is a
dynamic sequence of objects of potentially mixed(and changing) type.
>>>> # create a list of 2-tuples like (number, square)
>>>> [(x, x**2) for x in range(6)]
> [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>
> Why does this not need the .append or .insert? Square brackets around the
> whole line?
Because the list comprehension implicitly does an append
for you (see above)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list