Mari
Mari

Reputation: 29

Make list with while loop ? python3

I'm trying to make list contain (even numbers) with using while loop :

a=0
while a<8:
    a=a+2
    print(a,end=' ')
    t=list(a)
    print (t)

and how do I can make a code to division the numbers from the first list into two list: one for(even numbers) and the other for (odd numbers) ?

Upvotes: 0

Views: 4785

Answers (3)

BradTheBrutalitist
BradTheBrutalitist

Reputation: 299

Here is my answer to your question:

List = []
ListEven = []
ListOdd = []
Count = 0
while(Count < 11):
    print(Count, end = ' ')
    List.append(Count)
    if(Count % 2 == 0):
        ListEven.append(Count)
    elif(Count % 2 != 0):
        ListOdd.append(Count)
    Count += 1
print("\n""This is the main list:")
print(List)
print("This is the even list:")
print(ListEven)
print("This is the odd list:")
print(ListOdd)

I fixed the Count from Count += 2 to Count += 1 because you asked for a list of odds. The code you had would only produce even numbers. I hope this helped answer your question. :)

Upvotes: -1

Cory Kramer
Cory Kramer

Reputation: 117876

You can just create a list directly from each variable

>>> a = list(a)
>>> a
[1, 2, 3]

>>> b = list(b)
>>> b
['C', 'i', 't', 'y']

To make a list of even numbers using a while loop, you can do something like this

a = 0
t = []
while a < 8:
    t.append(a)
    a += 2

>>> print(t)
[0, 2, 4, 6]

Note that the above is just for learning purposes, this can be done using Python's range function more easily

>>> list(range(0, 8, 2))   # Evens
[0, 2, 4, 6]

>>> list(range(1, 8, 2))   # Odds
[1, 3, 5, 7]

Upvotes: 1

Zero
Zero

Reputation: 76917

Use list to convert.

In [1]: a=(1,2,3)

In [2]: list(a)
Out[2]: [1, 2, 3]

In [3]: b=('City')

In [4]: list(b)
Out[4]: ['C', 'i', 't', 'y']

Upvotes: 1

Related Questions