remove different elements of a list in python - 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']

Related

behaviour difference between list() function and [] in a conditional, the former behaves like string

Why does list(str) behaves as string here when [str] doesn't?
Is there a difference between these methods
Before someone marks this as a duplicate do link the answer because I've spent a fair bit of time scrawling through stackoverflow!
code
x = 'ar'
'a' in list(x)
#True
'a' in [x]
#False
l = list(x)
'a' in l
#True
type(list(x))
#list
type([x])
#list
This is because list() converts the string to a list where each letter is one element. But [] creates a list where the things inside are the elements. List() is converting the string to a list whereas [] is just putting the string in a list.
You can use debug output for clarifying such things. Like this:
x = 'ar'
print(list(x))
print([x])
Prints this:
['a', 'r']
['ar']
Then let's think logically. list(x) is a constructor of a list from the string, it creates a list of all characters of a given string. And [x] just creates a list with one item: x.
Because you are asking if the element 'a' is in the list. Which it is not, your only element is 'ar'. If you print([x]) the result should be ['ar']
[x] creates a single-element list, where the element is x. So if x = 'ar', then the resulting list is ['ar'].
list(x) casts the variable x into a list. This can work on any iterable object, and strings are iterable. The resulting list is ['a', 'r'].
The element 'a' is in the second list but not the first.

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

How to remove characters from each element in a list

I would like to remove the first two characters from each element (which are currently ints) that i have in a list. This is what i have:
lst = [2011,2012,3013]
I would like to get this
lst= [11,12,13]
I do not want a solution with some sort of replace 20 or 30 with '' however.
Given source= [2011,-2012,-3013] :
Result as ints, unsigned:
dest = [abs(x)%100 for x in source]
Result as ints, signed
dest = [(abs(x)%100)*(1 if x > 0 else -1) for x in source]
Result as strings, unsigned (preserves leading zeroes):
dest = list(map(lambda x : str(x)[-2:],source)
Result as strings, signed (preserves leading zeroes):
dest = list(map(lambda x : ("-" if str(x)[0]=="-" else "")+str(x)[-2:],source))
You can use:
list = [abs(number)%100 for number in list]
And it's a bad practice to name lists list. Use another name.
You can use module by 100,like:
my_list= [2011,2012,3013]
expected_list = [i%100 for i in my_list]
If you have negative numbers in my_list:
expected_list=[abs(i)%100 for i in my_list]
Or use string slicing:
expected_list = [int(str(i)[2:]) for i in my_list] #[2:],because you want to remove first two numbers
Please try avoid using reserved keywords as you variable name, as you have used list as your variable name.
Modulo:
just modulo each element with like 100
list= [2011,2012,3013]
for i in range(len(list)):
list[i] %= 100

Python : Checking if a string does not exist in a list of lists

I have a simple code that generates a list of lists and populates it with string "null", however when I try to check if "null" doesn't exist in the entire list of lists, it doesn't give me the result I'm expecting
lst = [ ['null']*4 for n in xrange(2) ]
print lst
if ('null' not in lst):
print "testing"
This code always prints "testing" and I don't know why.
Your explanation is appreciated
Thanks
Your list lst is not a list of strings but a list of lists of strings.
You might try:
if any('null' in lst2 for lst2 in lst):
as your test: that is, return True if there is a string 'null' in any of the sublists of your main list, lst.
flatten the list and then do a "is not in" check on the flattened list:
flattened = [x for x in sublist for sublist in lst]
if "null" not in flattened:
print("testing")

While loop with single quotes for a condition in 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.

Categories