While loop with single quotes for a condition in Python - python

I came across the following line of code in Python and I keep wondering what does it do exactly:
while '' in myList:
myList.remove('')
Thanks in advance.

It removes all empty strings from a list, inefficiently.
'' in myList tests if '' is a member of myList; it'll loop over myList to scan for the value. myList.remove('') scans through myList to find the first element in the list that is equal to '' and remove it from the list:
>>> myList ['', 'not empty']
>>> '' in myList
True
>>> myList.remove('')
>>> myList
['not empty']
>>> '' in myList
False
So, the code repeatedly scans myList for empty strings, and each time one is found, another scan is performed to remove that one empty string.
myList = [v for v in myList if v != '']
would be a different, more efficient way of accomplishing the same task. This uses a list comprehension; loop over all values in myList and build a new list object from those values, provided they are not equal to the empty string.

Put simply, it removes all empty strings from myList.
Below is a breakdown:
# While there are empty strings in `myList`...
while '' in myList:
# ...call `myList.remove` with an empty string as its argument.
# This will remove the one that is currently the closest to the start of the list.
myList.remove('')
Note however that you can do this a lot better (more efficiently) with a list comprehension:
myList = [x for x in myList if x != '']
or, if myList is purely a list of strings:
# Empty strings evaluate to `False` in Python
myList = [x for x in myList if x]
If myList is a list of strings and you are on Python 2.x, you can use filter, which is even shorter:
myList = filter(None, myList)

In Python, two single quotes '' or double quotes "" represent the empty string.
The condition to keep looping is while the empty string exists in the list, and will only terminate when there are no more empty strings.
Therefore, it removes all empty strings from a list.

Related

How to replace a character within a string in a list?

I have a list that has some elements of type string. Each item in the list has characters that are unwanted and want to be removed. For example, I have the list = ["string1.", "string2."]. The unwanted character is: ".". Therefore, I don't want that character in any element of the list. My desired list should look like list = ["string1", "string2"] Any help? I have to remove some special characters; therefore, the code must be used several times.
hola = ["holamundoh","holah","holish"]
print(hola[0])
print(hola[0][0])
for i in range(0,len(hola),1):
for j in range(0,len(hola[i]),1):
if (hola[i][j] == "h"):
hola[i] = hola[i].translate({ord('h'): None})
print(hola)
However, I have an error in the conditional if: "string index out of range". Any help? thanks
Modifying strings is not efficient in python because strings are immutable. And when you modify them, the indices may become out of range at the end of the day.
list_ = ["string1.", "string2."]
for i, s in enumerate(list_):
l[i] = s.replace('.', '')
Or, without a loop:
list_ = ["string1.", "string2."]
list_ = list(map(lambda s: s.replace('.', ''), list_))
You can define the function for removing an unwanted character.
def remove_unwanted(original, unwanted):
return [x.replace(unwanted, "") for x in original]
Then you can call this function like the following to get the result.
print(remove_unwanted(hola, "."))
Use str.replace for simple replacements:
lst = [s.replace('.', '') for s in lst]
Or use re.sub for more powerful and more complex regular expression-based replacements:
import re
lst = [re.sub(r'[.]', '', s) for s in lst]
Here are a few examples of more complex replacements that you may find useful, e.g., replace everything that is not a word character:
import re
lst = [re.sub(r'[\W]+', '', s) for s in lst]

How to remove the '' (empty string) in the list of list in python?

I want to remove the empty string ('') in the list of list in python.
My input is
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
My expected output should be like :
final_list=[['country'],['India']]
I am new to python i just to tried this (Note* below tried code is not intended)
final=[]
for value in final_list:
if len(set(value))==1:
print(set(value))
if list(set(value))[0]=='':
continue
else:
final.append(value)
else:
(final.append(value)
print(final)
Can some one help on me achieve the expected output? in the generic way.
You can use a list comprehension to check if any values exist within the sub list, and a nested comprehension to only retrieve those that have a value
[[x for x in sub if x] for sub in final_list if any(sub)]
Try the below
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)
output
[['country'], ['India']]
You can use a nested list comprehension with any that checks if list contains at least one string not empty:
>>> [[j for j in i if j] for i in final_list if any(i)]
[['country'], ['India']]
Assuming the strings inside the list of list doesn't contain , then
outlist = [','.join(innerlist).split(',') for innerlist in final_list]
But if the strings in the list of list can contain , then
outlist = []
for inlist in final_list:
outlist.append(s for s in inlist if s != '')
You could do the following (Using my module sbNative -> python -m pip install sbNative)
from sbNative.runtimetools import safeIter
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
for sub_list in safeIter(final_list):
while '' in sub_list: ## removing empty strings from the sub list until there are no left
sub_list.remove('')
if len(sub_list) == 0: ## checking and removing lists in case they are empty
final_list.remove(sub_list)
print(final_list)
Use a list comprehension to find all sublists that contain any value. Then use a filter to get all entries in this sublist that contain a value (here checked with bool).
final_list = [list(filter(bool, sublist)) for sublist in final_list if any(sublist)]

Check if each string (all of them) on a list is a substring in at least one of the strings in another

I am having a hard time trying to check if all of the strings in a python list are a subset of any string in another Python list.
Example:
I want to check if each string(all of them) of list1 is in at least one of the strings in the list2 and if it is, do something.
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']
In this example for instance it would return True.
You can use generator expressions combined with any/all functions:
>>> list1 = ['tomato', 'onions','egg']
>>> list2 = ['Two tomatos', 'two onions','two eggs','salsa']
>>> all(any(i in j for j in list2) for i in list1)
True
You can do with a single command using list comprehension, any, and all.
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']
result = all([any([keyword in string for string in list2]) for keyword in list1])
The first list comprehension [keyword in string for string in list2]checks that a keyword is at least present in all strings of list2 and produces a list of boolean. We use any to determine if any result was True.
The second list comprehension is built on top of the first list comprehension [any([keyword in string for string in list2]) for keyword in list1] and checks that all keywords were are least present in all the string of list2. We use all to check that all results are True.
As #Selcuk mentioned, you can do it more efficiently using generator expressions: the syntax is really is really close to list comprehensions:
result = all(any(keyword in string for string in list2) for keyword in list1)
You could go through the lists and execute something if it meets the condition that the word from list 1 exists in some element of list 2, for example:
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']
for i in list1:
for j in list2:
if i in j:
print("something to ", i, " and ", j)

replace substrings in list

I am looking forward to get rid of a space that is after each element in my list:
list1 = ['Aena', 'Cellnex Telecom', 'Amadeus', 'Abertis']
in order to obtain the list like this:
list1 = ['Aena','Cellnex Telecom','Amadeus','Abertis']
I have tried the following loop but returns the same initial list:
new_list = [stocks.replace(" ","") for stocks in list1]
and
new_list = [stocks.replace(", '",",'") for stocks in list1]
print(new_list)
Could anyone help me to obtain the desired list without the spaces?
I think you have to understand, that print(..) prints the representation of a list (which is a comma separated list surrounded by square brackets).
With the list comprehension, you alter the elements themselves. As far as I know you can't do much about how print prints the list itself. But you can write your own print method.
We can do this by using a join on the repr(..) of the elements, and surround it by square brackets, like:
print('[{}]'.format(','.join(repr(x) for x in list1)))
This prints:
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']
>>> print('[{}]'.format(','.join(repr(x) for x in list1)))
['Aena','Cellnex Telecom','Amadeus','Abertis']

remove different elements of a list in python

I have a list like this:
["Dog owner writes for dying cat", **datetime.datetime(2014,4,3,16,21,57), ''**, "Get him a ball", **datetime.datetime(2015,11,20,19,18,23), ''**]
There are many elements like datetime.datetime(2015,11,20,16,21,57) and '' in this list. How can I remove them?
Remark 1: the '' after datetime.datetime(2015,4,3,16,21,57) is a pair of single quotes.
Remark 2: apparently, the digits after datetime is the time with format year,month,day,hour,minute,second.
It makes more sense to make a new list with the items missing than it does to remove them from the list.
As a for-loop
cleaned = []
for i in my_list:
if type(i) is str and i != ""
cleaned.append(i)
As a list comprehension
cleaned = [ i for i in in my_list if type(i) is str and i != "" ]
You can simply filter out datetime objects and empty strings with list comprehension:
[x for x in lis if '' != x and type(x) is not datetime.datetime]
where lis is the original list. This will only remove datetime.datetime objects and empty strings. So in case the list contains lists, integers, etc.; those are not filtered out.
This generates:
>>> [x for x in lis if '' != x and type(x) is not datetime.datetime]
['Dog owner writes for dying cat', 'Get him a ball']

Categories