I am novice in Python.
I would like to enter 10 elements into the list.
Below program appends 10 elements to each of the list.
But below program prints 11 objects in list why?
I got this program from http://www.learnpython.org/page/Basic%20Operators link.
I wanted to know x = object(), what does it mean?
x = object()
y = object()
i = 0
# change this code
x_list = [x]
y_list = [y]
while(i < 10):
x_list.append((10))
y_list.append(11)
i = i + 1
#x_list = [x]
#y_list = [y]
big_list = x_list + y_list
print "x_list contains %d objects" % len(x_list) # prints 11 objects, #Why?
print "y_list contains %d objects" % len(y_list) # prints 11 objects, #Why?
print "big_list contains %d objects" % len(big_list)
print x_list.count(10)
print y_list.count(11)
print big_list.count(10)
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print "Almost there..."
if big_list.count(x) == 10 and big_list.count(y) == 10:
print "Great!"
The learnpython.org basic operators page provides some examples of using arithmetic operators in different contexts, including lists. Based on quickly reading the tutorial in that page, probably the answer that the page authors were after would be:
Which would create a list with 10 x:s in it.
You were using a loop to do that, which is much more flexible way. A more pythonic way to fill a list by using a loop would be e.g. to use list comprehensions:
or use a
forloop, then you don’t have to keep track of the index yourself: