emreakyol
emreakyol

Reputation: 87

Adding element to list by user

I cannot add all elements in the list. Just last element added. How can I add all entered elements ?

N = input("Enter the number of elemets: ")
for i in xrange(N):
    N = []
    a = input('%d. Element: ' %(i+1))
    N.append(a)    
print N

Upvotes: 0

Views: 27

Answers (1)

You are resetting N to an empty list on each iteration of the for-loop, then on the last iteration the last a value gets appended to the empty list, thus finishing with only one item in the N list.

Also, use a different variable name for the list (not the same variable that you defined for the input N)

N = input("Enter the number of elemets: ")
n = []                   # use a different variable name for this list
for i in xrange(int(N)): # cast N to integer
    a = input('%d. Element: ' %(i+1))
    n.append(a)          # append to the list `n` not `N`
print n                  # print the list

sample run:

Enter the number of elemets: 5
1. Element: 3
2. Element: 4
3. Element: 6
4. Element: 7
5. Element: 8
['3', '4', '6', '7', '8']

Upvotes: 1

Related Questions