Can't understand how For Loops work in Python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school assignment that involves me learning Python and I'm currently stuck on 'For Loops.' I'm stuck on understanding how they work and their syntax.
I have an example of code I've been trying to wrap my head around but just can't get it.
simple_list = ["Jack", "Dianne", "Alfred", "Erik"]
for x in simple_list:
print(x)
This is the code I've been focusing on and I don't understand why it prints a name from the simple list.
I also want to know what 'in' does as I couldn't find anything online that helped me understand it.
Thanks!

You can think like this:
for EVERY ITEM in THIS LIST:
print(THIS ITEM)

items = ["Jack", "Dianne", "Alfred", "Erik"]
for item in items:
print(item)
Look at it as a for each instead of the class for with indices.
for (each) item in items:
print(item)

For loops go over every item in a list. In this case you have a list
simple_list = ["Jack", "Dianne", "Alfred", "Erik"]
Now the for loop is going to look at every item in the list and do whatever is in the for loop with it. In this case, it will print it.
I'd recommend having a look at http://www.pythontutor.com/ to get a better feel for this sort of thing.

Related

I have a list in which items are getting added at any index dynamically , so i want to get the latest element added in list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
a = [5,2,7]
If 2 is the latest element added in a then return 2 .
You can use this syntax:
>>> list_ = [0, 1, 2]
>>> list_[-1]
2
There is no direct way of knowing how a list was modified. Python does not keep track of this information. This means you would have to keep a copy of the list before updating it and run something like
a = [5,2,7]
old_a = a.copy()
a[1] = 0
[old_a[i] for i,v in enumerate(a) if old_a[i]!=v]
However, if you are able to keep track of this, you are certainly able to keep track of the added value, and to run the tests before adding it to the new list. In summary, the design of what you are doing should probably be reconsidered.

Append to list or create new list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to add an element to a list, but the list might not exist yet. In which case, I'd create a list of that single element. It might be an entry in a dictionary. It's my responsibility to add to a particular field - hence the append. But, if it's the first time I'm doing it, the key doesn't even exist in the dictionary yet. Hence the set to a list of a single element.
So in a nutshell, the following
if 'dependencies' in userdata:
userdata['dependencies'].append('foo')
else:
userdata['dependencies'] = ['foo']
This feels very unpythonic and ugly. What are some better options?
use try...except like below:
try:
X.append('foo')
except NameError:
print("you need create list first. I create list for you. then append.")
X = ['foo']
EDIT : base on your editing question:
from collections import defaultdict
userdata = defaultdict(list)
userdata['dependencies'].append('foo')

Python function that returns independent value based off list input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the below JSON response, I want to write a function that:
runs through the response looking for a match of 'risk-level' = [medium OR high]
if match found returns the corresponding alert-id in a list / array format (I think we should use .append here)
if no match is found, exit the program (I'm pretty sure it would "exit()" here)
I have managed to get it to match / find one input and bring back that response, I'm just struggling with feeding it a list with an "OR" logic to bring back an independent result.
[
{'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},
{'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
{'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
{'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
]
You could use .append() as you mentioned, or, you could do this in a quick list comprehension.
Let's say your list is called events.
risky_events = [event['alert-id']
for event in events
if event['risk-level'] in {'medium','high'}]
The above code simply creates a list of matching risk levels. How would you use the snippet above to implement your exit() requirement? You would need to check if the list created above was empty. Give it a try.
What went wrong in the approach you took? Did you try using .append() yourself? Look up the Python docs section on lists to understand how append works, and give that approach a try.

Adding an unique item to a set [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The syntax for checking if an item is already in a list and then adding it to a list if it is not is:
foo = []
if item not in foo:
foo.append(item)
# do something
This can execute code on the condition that the item is not in foo. This syntax seems to duplicate the logic of a set datatype in python, yet the following syntax does not exist;
bar = set()
if not bar.add(item):
# do something
but add() returns nothing, so this is not possible. So how does one execute some logic conditionally on an item being in a set?
Note: the reason a set is desired is the operation of adding a unique value to a set is of O(1), whereas the same operation is O(n) on a list.
Just remove the if.
bar = set()
bar.add(item):
# do something
Note that you have foo.append(item) when using a list. The only thing that changes is the function name when you use a set.

Pandas error: String indices must be integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am not sure where I went wrong with my below code, where I used two for loops to firstly iterate statename and then iterate each dictionary that contains that specific statename.
I finally resolved this via my second code (the right code on the snip) however would be keen to know why the first didn't work.
The file used is a census file with statename, countyname (a subdivision of the state) and population being the columns.
Couldn't work with the following snip (on the left) where the error is 'string indices must be integers':
As others have already suggested, please read up on providing a Minimal, Reproducible Example. Nevertheless, I can see what went wrong here. When you loop through for d in census_df, this actually loops through the column names for your data frame, i.e. SUMLEV, REGION etc. This is presumably not what you had in mind.
Then your next line if d['STNAME']==c causes an error, as the message says, because string indices must be integers. In this instance you are trying to index a string using another string STNAME.
If you really want that first method to work, try using iterrows:
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for index, row in census_df.iterrows():
if row['STNAME']==c:
count+=1
list.append(count)
return(max(list))
answer_five()
Don't know why the pic is not coming up...sorry first timer here!
the first code that I tried which I have questions over are: (regarding string indices must be integers):
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for d in census_df:
if d['STNAME']==c:
count+=1
return list.append(count)
answer_five()
The second code helped resolve my question is:
max_county=[]
state_unique=census_df['STNAME'].unique()
def answer_five():
for c in state_unique:
df1=census_df[census_df['STNAME']==c]
max_county.append(len(df1))
return max(max_county)
answer_five()

Categories