List with empty indexes in python, how to remove? - python

I am trying to remove a position from an empty list, as a simple example that demonstrates or is trying to remove.
#Test about fruits
fruits = []
fruits.append('maça')
fruits.append('goiaba')
fruits.append('uva')
fruits.append('pera')
fruits.append('bananna')
fruits[1] = []
print (fruits)
Output : ['maça', [], 'uva', 'pera', 'bananna']
Desired output ['maça', 'uva', 'pera', 'bananna']
Just remembering that it is a simple example, so I can apply it in a more robust program that I am developing that presents the same problem of having a "position" in the list with a 'null' or empty value in this case.

Use pop() to remove an element from a list by its index, rather than assigning an empty value to the index.
fruits.pop(1)
or del
del fruits[1]
pop() allows you to retrieve the value being removed at the same time.

You can use
del fruits[1]
See Difference between del, remove and pop on lists for the differences.

Related

Python: How can I use an enumerate element as a string?

I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.
for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call
https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.
EDIT:
for i,j in enumerate(dict1.keys()): j = somethingElse
EDIT2:
I think the problem may be with pandas. The first line works, not the second.
for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])
EDIT3:
That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:
for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])
EDIT4:
According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:
listOfFrame = []
for j in dict.keys():
j = pd.DataFrame(dict[j]['Values'])
listOfFrame.append(j)
Indeed j will be a str (or whatever else type of key you are using in dict).
The actual problem is with the loop body, as the error message states:
str(j) = somethingElse
is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.
Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:
dfs = []
for val in dict1.values():
dfs.append(pd.DataFrame(val['Values']))
However, this would normally written without an explicit loop in Python, for instance by using list comprehension:
dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]
From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names

Appending "," to every item in a List of integers

I want to append "," and then the item index to every item in a list of integers.
I know that I need to convert the integers to strings before I do that, but even if I do that, it isn't working:
(I use Python 3.7.3)
for element in mylist:
element = str(element)
element = "{0},".format(element)
element = element + mylist.index(element)
What I want:
mylist = ["97,0", "569,1", "39,2", "230,3",....]
Possibly someone can link to a question of which this is a duplicate, but I don't know my way around that well yet.
You want list comprehensions, and the enumerate function.
new_list = ["{0},{1}".format(item, index) for (index, item) in enumerate(old_list)]
If you absolutely positively need to change the list in-place, then you can iterate over a copy of that list and do just that.
for i, val in enumerate(mylist[:]): # note the empty slice there -- that creates a whole copy!
mylist[i] = f"{val},{i}"
Technically since you're not adding or removing elements, you are allowed to do this without that copy
for i, val in enumerate(mylist):
mylist[i] = f"{val},{i}"
but this is a dangerous habit to get into without fully understanding what you can and cannot do to a list that you're iterating over. If your goal was to do this but also remove the 10th element (or etc), you would have to make a copy. Similarly if you wanted to insert a new element before the value 97, or etc.
As general best practice, you should avoid mutating the list if possible and produce a new one using a list comprehension as recommended in ShapeOfMatter's answer
mylist = [97,0, 569,1, 39,2, 230,3]
for items in mylist:
(str(items))
print('\"{0}\"'.format(items))
Here is the solution to your question, if I understood it correctly you wanted to add for every item in the list "".

How to remove last item of a list/array no matter the length

I am trying to remove the last item of a list/array even if there are duplicate items
EG
list = ["h","e","l","l","o"," ","t","h","e","r,"e"]
It would remove the final "e" but not the second and ninth "e"
I have already tried
finalSentence.remove([finalSentence[len(finalSentence)-1]])
However this removes a random letter, I know this is because it is removing a letter rather than item number and python does not know which one to choose so it is a random one that is removed. But I do not know another way to get this to work
.remove removes the first occurrence of an item. You could do something like
del my_list[len(my_list) - 1]
Or simply:
del my_list[-1]
Or, probably the most idiomatic:
my_list.pop()
Note, the above methods work in (amortized) constant time, and they modify my_list in-place.
Do not use list as a variable name, as it will probably conflict with the built-in type. But try this:
mylist = mylist[:-1]
That uses a slice from the beginning of the list up to but not including the last element. If the list is empty, there is no apparent change. If you want an error to be raised, you should use one of the methods of #juanpa.arrivillaga.

How do i remove an item from a list and store it into a variable in python

so i want to remove an item from a list and store it into the variable at the same time in python. I tried a sample code like this:
rvals = []
rvals.append("row")
r = rvals.remove("row")
print(r)
but it turns out this doesnt really work and it gives r a NoneType value instead of removing what i wanted and storing it. Is there a way to do this?
list.remove(x)
Remove the first item from the list whose value is x. It is an error
if there is no such item.
So, as stated in the docs, you will not get the value returned.
This can help:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop(rvals.index(value))
Or just use pop(), if you only want to remove and get the last inserted item:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop()
Output:
row
Printing a removed element from the list using remove() method generally results in None.
Hence, a better approach is to, first store the element to be removed and then remove it from the list.

How do I remove an item from a Python list by value?

If I wanted to remove an item by its value instead of its index what would I do?
animals = ['tiger', 'snake', 'penguin','giraffe']
Say I wanted to remove 'penguin' without typing del animals[2] how would I go about it?
I've tried typing del animals['penguin'] but it doesn't work...
You have to either find the index, or filter the list.
Finding the index:
del animals[animals.index('penguin')]
Or, you could just remove the value:
animals.remove('penguin')
where list.remove() is documented as being equilalent to the del listobj[listobj.index(value)] version above.
Either of these can raise an IndexError if 'penguin' is not part of the list. If there is more than one copy of the value in the list, only the first such copy is removed.
Filtering would remove all such copies:
animals = [a for a in animals if a != 'penguin']
This will not raise an exception; it builds an entirely new list of values that are not equal to 'penguin'.
animals.remove("penguin")
Right? Granted it only removes the first value, but it will remove it by value not index. And will not require building a new list or require an extra call to lookup the index of the given value.
One more way to filter the list which wasn't mentioned by Martijn Pieters is to use built-in filter function:
animals = filter(lambda x: x != 'penguin', animals)

Categories