I am trying to add to an empty list in python and I am having
trouble. Ill give an example of the code to see if anyone can help
me out....

num = 0
mylist = []

while num < 10:
num = num + 1
mylist = mylist + num

for item in list:
print item

Recommended Answers

All 5 Replies

To do it the way you're trying to do it, use this:

>>> num = 0
>>> mylist = []
>>> 
>>> while num < 10:
...     num += 1
...     mylist += [num]
...     
>>> for item in mylist:
...     print item
...     
1
2
3
4
5
6
7
8
9
10
>>>

Notice I put brackets around num since you have to add a list to a list when using the + operator. Other methods would be to use mylist.append(num) or mylist.insert(index, num) . I also changed your x = x + y statements to x += y , which is identical.

HTH

Some corrections:

num = 0
mylist = []

while num < 10:
    num = num + 1
    mylist.append(num)

print(mylist)

for item in mylist:
    print(item)

So what you basically want is to fill the list with a sequence of numbers? Why?

I'm not getting it to print anything! I'll post the exact code I am working with... I'm trying to convert from deci to binary and print the binary number using the list method.

remain = 0
quo = 1
mynum = []

deci = int(raw_input("Please enter a decimal integer:"))

while quo != 0:

quo = deci / 2

remain = deci / 2

mynum.append(remain)

print(mylist)

for item in mynum:
print item

Member Avatar for masterofpuppets

"I'm not getting it to print anything! I'll post the exact code I am working with... I'm trying to convert from deci to binary and print the binary number using the list method."
...
so you're trying to convert a number from decimal to binary??
here's a hint how to do that :)

number = 14
14 / 2 = 7, remainder = 0
7 / 2 = 3, remainder = 1
3 / 2 = 1, remainder = 1
1 / 2 = 0, remainder = 1

therefore 14 in binary is 1110
you can use l.insert( 0, num ) to deal with the reverse order, where l is a list

hope that helps! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.