Delete Item from specific location in list in Python [duplicate] - python

This question already has answers here:
How to remove an element from a list by index
(18 answers)
Closed 8 years ago.
I'm writing a statistics program which will maintain a list of float values. The program will implement the following menu:
Add value to list
Delete value from list (by value)
Delete value from list (by location in list)
Display list
Exit
I've written everything except the third option. I can't figure out how to get it done. How would one do that?

In Python you can delete an item from a list by referencing it. Like this:
del list[location]

Related

Possible to convert string to a named variable or alternative? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
generating variable names on fly in python [duplicate]
(6 answers)
Closed 3 years ago.
I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.
The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.
Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?
list_1=['A','B']
list_2=['C','D']
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list):
for ticker in list:
if new_ticker in list:
return
else:
list.append(new_ticker)
list.remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
You key the needed lists by name in a dictionary:
ticker_directory = {
"list_1": list_1,
"list_2": list_2
}
Now you can accept the name and get the desired list as ticker_directory[assigned_list].
list_1=['A','B']
list_2=['C','D']
lists = {
'list_1':list_1,
'list_2':list_2
}
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list_name):
if old_ticker not in lists[list_name]:
return
else:
lists[list_name].append(new_ticker)
lists[list_name].remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
print(lists[assigned_list])
This is the complete program from what i perceived.
#prune already answered this, I have just given the whole solution
There are at least two possibilities:
1 As noted in comments kind of overkill but possible:
Use eval() to evaluate string as python expressions more in the link:
https://thepythonguru.com/python-builtin-functions/eval/
For example:
list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))
2 Second
Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.
list_name = 'list_1'
locals()[list_name].append(new_ticker)

(Python) Can I store the functions themselves, but not their value, in a list [duplicate]

This question already has answers here:
Python Argument Binders
(7 answers)
Closed 8 months ago.
As you can see from the code below, I'm adding a series of functions to a list.
The result is that each function gets ran and the returned value is added to the list.
foo_list = []
foo_list.append(bar.func1(100))
foo_list.append(bar.func2([7,7,7,9]))
foo_list.append(bar.func3(r'C:\Users\user\desktop\output'))
What I would like to know is, is it possible to have the function stored in the list and then ran when it is iterated upon in a for loop?
Yeah just use lambda:
foo_list = []
foo_list.append(lambda: bar.func1(100))
foo_list.append(lambda: bar.func2([7,7,7,9]))
foo_list.append(lambda: bar.func3(r'C:\Users\user\desktop\output'))
for foo in foo_list:
print(foo())

Value changes in new list impact previous list values, within a list of lists [duplicate]

This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 4 years ago.
I am looking to randomly generate a list and change one element in the list to create a new list. Whilst keeping track of all the generated lists.
For example:
values_possible = [0,0.5,1]
combinations = []
combinations.append([random.choice(values_possible) for i in range(8)])
lets say this generates
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
then if I copy this list and change one element, say combinations[1][1]
# set a new list to equal the first and then change one element
combinations.append(combinations[0])
combinations[1][1] = 0.33
print(combinations[0])
print(combinations[1])
this returns
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
it seems both combinations[0][1] and combinations[1][1] have changed to 0.33. Is there a way to solve this? May I ask why this happens and what I am misunderstanding about lists? I had expected the following output:
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
The short answer to your question is using colon:
combinations.append(combinations[0][:])
Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.
If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.
You can also take a look at this question and answer: python list by value not by reference
I hope this helps.
use
combinations.append(list(combinations[0]))
to append a copy of the first element.

Select each element of the list (using loop) [duplicate]

This question already has answers here:
Loop through each element of the list [closed]
(2 answers)
How does a Python for loop with iterable work?
(7 answers)
Closed 8 years ago.
Hi i am new to python and i am trying to build a function which will select each element of the list at a time,store each element in a variable and do something (using a loop)
StrLst = ['aaa','bbbaaa','cccbbb','aaabbb']
now i want the first element of the list which will be stored in a variable
LstEle = list[0] #i.e. LstEle = aaa
use the LstEle variable
and then go to the next element and do the same keep doing this for the whole list
You can use a for-loop in order to achieve what you want.
for LstEle in StrLst:
# do something with LstEle
In each iteration the current element will be accessible through LstEle.

python default dictionary calling key values [duplicate]

This question already has answers here:
Python Dictionary DataStructure which method d[] or d.get()?
(5 answers)
Closed 8 years ago.
I have written a bit of code using
setting value
dic["key"] = "someval"
and fetching it the same way
print dic["key"]
then I discovered that an alternative way to fetch a dictionary value is to use
print dic.get("key")
I want all my code to use the same method, so should I rewrite all using dic.get("key") ?
If you have a flat dictionary and you want to add or modify a key/value pair, than the best way is to use a simple assignment:
h[key] = value
The get method is useful when you want to get a value from a dictionary for existing keys or use a default value for non-existing keys:
print h.get(key, "Does not exist!")

Categories