python modify item in list, save back in list - python

I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index
I'm having difficulty getting an item back into the same index
for item in list:
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[item] = item
print item
now I get an error
TypeError: list indices must be integers, not str
due to this line list[item] = item
which makes sense! but I do not know how to put the item back into the list at that same index using python
what is the syntax for this? Ideally the for loop can keep track of the index I am currently at

You could do this:
for idx, item in enumerate(list):
if 'foo' in item:
item = replace_all(...)
list[idx] = item

You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item

A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
See enumerate.

For Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"

Related

remove items from specific place on the list

I want to remove some items from specific places. for example, I have list [a,b,c,d,e,f,g,h,i]. the number of items in this list constantly changes.
That is why I need special method that is helps to remove items from same place. Now the modified list should be like that: list [a,b,c,d,e,f,i]. g and h should always be removed.
Do you want to remove the second- and third-last item from the list?
This can be achieved like this:
del lst[-3:-1]
If you create dictionaries with necessary indexes you can use them to create a new list.
lst = ['a','b','c','d','e','f','g','h','i']
other = ['a','y','b','c','d','e','g','h','l']
indexed_lst = {i: item for i, item in enumerate(lst)}
indexed_other = {i: item for i, item in enumerate(other)}
[item for i, item in indexed_lst.items() if indexed_lst.get(i, None) != indexed_other.get(i, None) ]
You can remove from the list either by index or by value. In either case it is a good practice to check if the index/value is present in the list. As for removing an item from the list you could use one of the below based on what info is available / output required.
Remove an item by index and get its value: pop()
# where i is the index of the value to be removed
if i < len(lst)
result = l.pop(i)
Remove items by index or slice: del()
# where i is the index of the value to be removed
if i < len(lst) :
lst.del(i)
Remove an item by value: remove()
# where `h` is the value to be removed
if 'h' in lst:
lst.remove('h')
You could also remove items from a list based on a given condition, in which case you could use list comprehensions
l = list(range(10))
# Remove all the odd numbers
print([i for i in l if i % 2 != 0])
ahh i understand your answer, if you use index like this
Remove items by index, specific place
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for index,item in enumerate(lst) if index != 6 and index != 7]
print(lst)
or Remove items by Value
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
Use the .pop() to pop off any given index off the list
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
if you have more input, tell me

python: replace datetime.date with isoformat() in list

I want to replace the datetime objects in this list:
a = [
[datetime.date(2019,1,1), 100],
[datetime.date(2019,1,2), 187],
]
So I have created this function:
def date_to_iso(rows):
for line in rows:
for item in line:
if isinstance(item, datetime.date):
item = item.date().isoformat()
return tempL
Can anybody tell me why this function is not changing the list?
when you're assigning back to item, you're just re-using the item name, but the old reference is "lost". Assign to the original list with the index instead (using the idiomatic method with enumerate to yield the index and the element:
def date_to_iso(rows):
for line in rows:
for i,item in enumerate(line):
if isinstance(item, datetime.date):
line[i] = item.date().isoformat()
this code uses item as read-only, until it's necessary to replace it in the original list.
Note that line[i] = ... still uses the original line object, that's why it works.
Another way would be to use a list comprehension to fully rebuild the data, which would require slice assignment to rows[:] to simulate in-place change for rows:
def date_to_iso(rows):
rows[:] = [[item.date().isoformat() if isinstance(item, datetime.date)
else item for item in line] for line in rows]

isolating a sub list from a big list in python

I have a big list in python like this small example:
small example:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV', 'MDHTEGSPAEEPPAHAPSPGKFGERPPPKRLTREAMRNYLKERGDQTVLILHAKVAQKSYGNEKRFFCPPPCVYLMGSGWKKKKEQMERDGCSEQESQPCAFIGIGNSDQEMQQLNLEGKNYCTAKTLYISDSDKRKHFMLSVKMFYGNSDDIGVFLSKRIKVISKPSKKKQSLKNADLCIASGTKVALFNRLRSQTVSTRYLHVEGGNFHASSQQWGAFFIHLLDDDESEGEEFTVRDGYIHYGQTVKLVCSVTGMALPRLIIRKVDKQTALLDADDPVSQLHKCAFYLKDTERMYLCLSQERIIQFQATPCPKEPNKEMINDGASWTIISTDKAEYTFYEGMGPVLAPVTPVPVVESLQLNGGGDVAMLELTGQNFTPNLRVWFGDVEAETMYRCGESMLCVVPDISAFREGWRWVRQPVQVPVTLVRNDGIIYSTSLTFTYTPEPGPRPHCSAAGAILRANSSQVPPNESNTNSEGSYTNASTNSTSVTSSTATVVS']
in the file there are many items and each item is a sequence of characters. I want to make a new list in which every item has only one W. the expected output for the small example would be like the expected output.
expected output:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV']
I am trying to do that in python and wrote the following code:
newlist = []
for item in mylist:
for c in item:
if c == W:
newlist.append(item)
but it does not return what I want. do you know how to fix it?
Use .count
Ex:
res = []
mylist = ['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV', 'MDHTEGSPAEEPPAHAPSPGKFGERPPPKRLTREAMRNYLKERGDQTVLILHAKVAQKSYGNEKRFFCPPPCVYLMGSGWKKKKEQMERDGCSEQESQPCAFIGIGNSDQEMQQLNLEGKNYCTAKTLYISDSDKRKHFMLSVKMFYGNSDDIGVFLSKRIKVISKPSKKKQSLKNADLCIASGTKVALFNRLRSQTVSTRYLHVEGGNFHASSQQWGAFFIHLLDDDESEGEEFTVRDGYIHYGQTVKLVCSVTGMALPRLIIRKVDKQTALLDADDPVSQLHKCAFYLKDTERMYLCLSQERIIQFQATPCPKEPNKEMINDGASWTIISTDKAEYTFYEGMGPVLAPVTPVPVVESLQLNGGGDVAMLELTGQNFTPNLRVWFGDVEAETMYRCGESMLCVVPDISAFREGWRWVRQPVQVPVTLVRNDGIIYSTSLTFTYTPEPGPRPHCSAAGAILRANSSQVPPNESNTNSEGSYTNASTNSTSVTSSTATVVS']
for item in mylist:
if item.count("W") == 1:
res.append(item)
print(res)
or
res = [item for item in mylist if item.count("W") == 1]
Output:
['MLEEDMEVAIKMVVVGNGAVGKSSMIQRYCKGIFTKDYKKTIGVDFLERQIQVNDEDVRLMLWDTAGQEEFDAITKAYYRGAQACVLVFSTTDRESFEAV']
The problem is you are iterating each character in each string and appending when a condition is met. Moreover, your logic can't "undo" a list.append operation if another W is found. So if W is met twice in a string, you are appending twice.
Instead, you can use a list comprehension with list.count:
res = [i for i in L if i.count('W') == 1]

Taking a list of items and displaying a value from each item as a string

I have a function that takes a list of items i.e. [item_1, item_2] etc.
Each item itself is a dictionary on another page. i.e. item_1 {key: value, etc}
I want to display the value of the key (called "name") for each item in the list.
For example if the input to the function, list_of_items() is [item_1, item_2]
Should return 'name of item 1, name of item 2' as a string separated by commas.
new_list = []
for i in items:
new_list.append(i["name"])
return str(new_list).strip('[]')
This code returns "'name of item 1', 'name of item 2'" and it is the closest I have gotten.
How can I return the string I want?
You can use str.join() to join the list of strings into a single string. Example -
new_list = []
for i in items:
new_list.append(i["name"])
return ','.join(new_list)
This can be simplified using the below list comprehension -
return ','.join([i['name'] for i in items])
Demo -
>>> items = [{'name':'a'},{'name':'b'},{'name':'c'}]
>>> ','.join([i['name'] for i in items])
'a,b,c'
The answer from #AnandSKumar is perfect. In addition, note that you don't actually have a function in the code that you provided. A function in python begins with the def statement. So copying some code from #AnandSKumar, you have the following function:
def dictsName2str ( listOfDicts ) :
return ','.join([i['name'] for i in listOfDicts])
Then you can call your function with the following code:
>>> items = [{'name':'a'},{'name':'b'},{'name':'c'}]
>>> myStr = dictsName2str( items )

Add item into array if not already in array

How can I insert item into the array if its not already there?
This is what I tried:
[..]
k = []
for item in myarray:
if not item in k:
print("Item is in array already.")
k[] = item
Your code has the right idea but just use k.append(item) instead of k[] = item.
Also it is cleaner to say if item not in k:
k[] = item is invalid syntax. All you need to do is just remove that line and use list.append()
for item in myarray:
if not item in k:
print("Item is in array already.")
k.append(item)
list.append() adds an item to the end of the list.
If you don't care about the order of the items in the list, you can convert it to a set to filter out any duplicates.
k = list(set(myarray))
Or if k already contains something...
k = [...] # optionally non-empty array
k = list(set(k) | set(myarray))
What that does is convert both myarray and k into sets, and combines them so that the result is a unique list that containing the contents of both k and myarray.

Categories

Resources