Removing a certain word from a list - python

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

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']

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.

Related

Taking the 'product' of lists

Suppose that I am given a list of strings, e.g. list = ['a', 'b', 'c']. I am also given a list of 'continuation strings', e.g. continuations = ['d', 'f'], and I want to form a list of all possible sequences formed by combining the original list with a continuation letter. In this example, I want to obtain the list of lists: new_list = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]. To do this, I tried
new_list = []
for element in continuations:
# Make a copy of the original list
copy = list
# Add a continuation letter to the original list
possible_sequence = copy.append(element)
# Add the new list to the list of lists
new_list.append(possible_sequence)
But this generates [None, None]... Can anyone explain what is wrong with my code?
# it is a bad practice to shadows built-in name, so I changed 'list' name to 'abc_list'
abc_list = ['a', 'b', 'c']
continuation = ['d', 'f']
print([abc_list + [x] for x in continuation])
Output: [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
CODE
main_list = ['a', 'b', 'c']
continuations = ['d', 'f']
new_list = []
for element in continuations:
temp_list = main_list.copy()
temp_list.append(element)
new_list.append(temp_list)
print(new_list)
OUTPUT
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
Here's how I would do it.
create a list to store the possible sequences
iterate through the continuation list
copy the original list
append the continuation letter to the copied list
append the copied list to the possible list
def combine_list(list_, cont_list):
# create a list to store the possible sequences
possible_list = []
# iterate through the continuation list
for j in cont_list:
# copy the original list
l2 = list_.copy()
# append the continuation letter to the copied list
l2.append(j)
# append the copied list to the possible list
possible_list.append(l2)
return possible_list
l = ['a', 'b', 'c']
c = ['d', 'f']
print(combine_list(l, c))
Output:
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
Edit
What's wrong with your code?
If you want to copy a list you need to it with list.copy(). If you just do copy = list you are not creating a new list object. if you make changes in copy all changes will apply to list also.
The list.append(element) function does not return a list object it returns None that's why your result looks like this [None, None] you appended None twice.
In Python, append modifies the list it is called on and doesn't return anything (technically it returns None, which is why you ended up with a list full of None). That means that you cannot store the result of append in a variable.
my_list = []
foo = my_list.append(1)
print(foo) # Prints 'None' because that's all that append returns
print(my_list) # Prints '[1]' because the value got added to the original list by append
This is the big difference between lists and strings in Python that beginners sometimes get confused about. Strings are immutable which means they cannot be changed. So methods such as replace return a new string, because they cannot modify the original string. Lists, on the other hand, are mutable, meaning they can be modified. So methods on lists such as append or pop modify the list they are called on rather than returning a new one.
my_string = "Python"
# Needs to be stored in a new variable,
# the original string cannot be modified
new_string = my_string.replace("n", "k")
print(my_string) # Still the original value, Python
print(new_string) # The new modified value, Pythok
my_list = [1, 2]
my_list.append(3) # Modified the list itself, no need to store anything new
print(my_list) # [1, 2, 3]
Also, note that it is an extremely bad idea to call one of your lists list as list is a keyword in Python. (It is used to construct new lists, e.g. list(range(10)) creates a list [0, 1, ..., 9]).

How to create whitespace between certain list elements?

I found a post asking about how to create whitespace in all list elements (Adding spaces to items in list (Python)), but I haven't found any posts asking about how to create whitespace in only specific elements of a list.
I'm wondering how to create a space between certain element characters in a list.
If I have a list like this:
lst = ['a', 'bb', 'c', 'bb']
How can I make a new list with a space between all 'bb' occurrences in a list to look like this?:
lst_new = ['a', 'b b', 'c', 'b b']
I've tried using .replace('bb', 'b" "b'), but I get 'b' and 'b' as separate list elements. Is there a specific notation for "whitespace" in Python? Or is there another way to approach this?
lst = ['a', 'bb', 'c', 'dd']
lst_new = []
for elem in lst:
if len(elem) > 1:
lst_new.append(' '.join(list(elem)))
else:
lst_new.append(elem)
print(lst_new)
Here's a very simple and easy to understand way to do it. The main idea is to check if the length of the elem is greater than 1, then use list to "split" the string. You can then join the string with a whitespace by using join.

How to make a n-dimention list with one dimention lists with a loop

I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)

Creating an irregular list of lists from a single list

I'm trying to create a list of lists from a single list. I'm able to do this if the new list of lists have the same number of elements, however this will not always be the case
As said earlier, the function below works when the list of lists have the same number of elements.
I've tried using regular expressions to determine if an element matches a pattern using
pattern2=re.compile(r'\d\d\d\d\d\d') because the first value on my new list of lists will always be 6 digits and it will be the only one that follows that format. However, i'm not sure of the syntax of getting it to stop at the next match and create another list
def chunks(l,n):
for i in range(0,len(l),n):
yield l[i:i+n]
The code above works if the list of lists will contain the same number of elements
Below is what I expect.
OldList=[111111,a,b,c,d,222222,a,b,c,333333,a,d,e,f]
DesiredList=[[111111,a,b,c,d],[222222,a,b,c],[333333,a,d,e,f]]
Many thanks indeed.
Cheers
Likely a much more efficient way to do this (with fewer loops), but here is one approach that finds the indexes of the breakpoints and then slices the list from index to index appending None to the end of the indexes list to capture the remaining items. If your 6 digit numbers are really strings, then you could eliminate the str() inside re.match().
import re
d = [111111,'a','b','c','d',222222,'a','b','c',333333,'a','d','e','f']
indexes = [i for i, x in enumerate(d) if re.match(r'\d{6}', str(x))]
groups = [d[s:e] for s, e in zip(indexes, indexes[1:] + [None])]
print(groups)
# [[111111, 'a', 'b', 'c', 'd'], [222222, 'a', 'b', 'c'], [333333, 'a', 'd', 'e', 'f']]
You can use a fold.
First, define a function to locate the start flag:
>>> def is_start_flag(v):
... return len(v) == 6 and v.isdigit()
That will be useful if the flags are not exactly what you expected them to be, or to exclude some false positives, or even if you need a regex.
Then use functools.reduce:
>>> L = d = ['111111', 'a', 'b', 'c', 'd', '222222', 'a', 'b', 'c', '333333', 'a', 'd', 'e', 'f']
>>> import functools
>>> functools.reduce(lambda acc, x: acc+[[x]] if is_start_flag(x) else acc[:-1]+[acc[-1]+[x]], L, [])
[['111111', 'a', 'b', 'c', 'd'], ['222222', 'a', 'b', 'c'], ['333333', 'a', 'd', 'e', 'f']]
If the next element x is the start flag, then append a new list [x] to the accumulator. Else, add the element to the current list, ie the last list of the accumulator.

Creating a list that gives a specific value at even indexes and another value at odd indexes

I want to create a list say chelsea_fc that will populate the value "EPL Champions" in even indexes and "Manager Sacked" at odd indexes till a given range. (dont want to hard code the range)
I am getting confused as how to do it. Please help
Literally write it as you would say it!
>>> ['a' if i % 2 else 'b' for i in range(10)]
['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']
You can do this (or any other list that repeat itself) like this:
chelsea_fc = ['Manager Sacked', 'EPL Champions']*(range_of_choice/2)
print(chelsea_fc)

Categories