-1

I have had to put items into a list but because I did not know how many items it would be I had to set the list up as

matching_words=["none"]*100

Once all the words have been added, I then want the remaining "none"'s to be removed so the list is only as long as the number of words added is. How can this be done. I tried this

newMatching_words=matching_words.remove("ABCDEFG")
print(newMatching_words)

This returned

None
R watt
  • 67
  • 7

2 Answers2

4

You should have started with an empty list and appended items to it:

matching_words = []

for word in source_of_words:
    matching_words.append(word)

print(matching_words)

Also, just so you know about the remove method:

print(matching_words)

matching_words.remove('bar')

print(matching_words)

Sample Output:

['foo', 'bar', 'baz']
['foo', 'baz']
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

There are some things which i want to explain when you need to define list length and when you don't.

First, you don't need to define list length at the beginning in general case:

You can simply do :

#Just for example

new_list=[]

for i in map(chr,range(97,101)):
    new_list.append(i)

print(new_list)

output:

['a', 'b', 'c', 'd']

Yes you need to define a empty list when you have another list for index items like this:

matching_words=[None]*10

index_list=[4,3,1,2]

for i in zip(list(map(chr,range(97,101))),index_list):
    matching_words.insert(i[1],i[0])

print(matching_words)

output:

[None, 'c', 'd', None, None, 'b', None, 'a', None, None, None, None, None, None]
['c', 'd', 'b', 'a']

In this program we have to insert chracter in that order in which the index_list showing the intergers , so if we try without defining list before then as you can see we are inserting first chr at index 4 which is not there.

In your case if you have second situation then try this to remove rest of none:

print([i for i in matching_words if i!='none'])

otherwise if you should go with first case.

Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88