A few choices, in descending order of Pythonicity:
for index, item in enumerate(lst): # note: don't use list
if not index: # or if index == 0:
# first item
else:
# other items
Or:
first = True
for item in lst:
if first:
first = False
# first item
else:
# other items
Or:
for index in range(len(lst)):
item = lst[i]
if not index:
# first item
else:
# other items
Answer from jonrsharpe on Stack OverflowHello everyone, for some reason I can't understand the for loop only iterates through the 1st object in my for loop. I have no idea why this is happening.
The code (ignore the foreign language it's just the keys are in a different language):
https://pastebin.com/rS5JFiAd
My json file (again, ignore the foreign language):
https://pastebin.com/2Bfdpbts
A few choices, in descending order of Pythonicity:
for index, item in enumerate(lst): # note: don't use list
if not index: # or if index == 0:
# first item
else:
# other items
Or:
first = True
for item in lst:
if first:
first = False
# first item
else:
# other items
Or:
for index in range(len(lst)):
item = lst[i]
if not index:
# first item
else:
# other items
You can create an iterator over the list using iter(), then call next() on it to get the first value, then loop on the remainder. I find this a quite elegent way to handle files where the first line is the header and the rest is data, i.e.
list_iterator = iter(lst)
# consume the first item
first_item = next(list_iterator)
# now loop on the tail
for item in list_iterator:
print(item)
python - returning only first element from for loop - Stack Overflow
python - "For" loop first iteration - Stack Overflow
Select first in for loop
Python: My for loop doesnt work. Only checks first element - Stack Overflow
Something like this should work.
for i, member in enumerate(something.get()):
if i == 0:
# Do thing
# Code for everything
However, I would strongly recommend thinking about your code to see if you really have to do it this way, because it's sort of "dirty". Better would be to fetch the element that needs special handling up front, then do regular handling for all the others in the loop.
The only reason I could see for not doing it this way is for a big list you'd be getting from a generator expression (which you wouldn't want to fetch up front because it wouldn't fit in memory), or similar situations.
You have several choices for the Head-Tail design pattern.
seq= something.get()
root.copy( seq[0] )
foo( seq[0] )
for member in seq[1:]:
somewhereElse.copy(member)
foo( member )
Or this
seq_iter= iter( something.get() )
head = seq_iter.next()
root.copy( head )
foo( head )
for member in seq_iter:
somewhereElse.copy( member )
foo( member )
People whine that this is somehow not "DRY" because the "redundant foo(member)" code. That's a ridiculous claim. If that was true then all functions could only be used once. What's the point of defining a function if you can only have one reference?
you're looping over all the tables, but not looping over all the items in each table.
def pull_active(url):
for i in key_data2:
for td in i.findall('td', class_='colText'):
label = td.find('a', class_='truncateMeTo1')
value = td.find('td', class_='colPrimary')
if a and col:
stock_list.append((label.get_text(), value.get_text()))
print(stock_list)
import requests
from bs4 import BeautifulSoup
stock_list = []
url='https://markets.on.nytimes.com/research/markets/overview/overview.asp'
response = requests.get(url)
if not response.status_code == 200:
print(respose.status_code)
results_page = BeautifulSoup(response.content,'lxml')
key_data=results_page.find('table',class_="stock-spotlight-table",id="summ_vol+")
key_data2=key_data.find('tbody').find_all('tr')
def pull_active(url):
for i in key_data2:
label = i.find('a', class_='truncateMeTo1').get_text()
value = i.find('td', class_='colPrimary').get_text()
stock_list.append((label, value))
print(stock_list)
pull_active(url)
key_data2=key_data.find_all('tbody')
This is the line that is causing issues in your solution. table row represents each item. So you need to find all the rows and iterate throught that
From what i understood, you want to only print the first five elements of each row?
In that case, you can iterate over the list to get the rows, and then slice the rows. An implementation of this could look something like this:
for row in allUserDetails:
for element in row[0:5]: # the rows have been sliced to only show element 0 - 5
print(element)
print("-" * 25)
I would suggest using another for loop inside the row loop, which will help pick out n elements from the row
for row in allUserDetails: #Loops through all arrays in the 2D array
for i in range(5): #Loops through the first five elements of the row
print(row[i])
for row in allUserDetails will set the variable row to an array of Strings as defined in your 2D array.
for i in range(n) will loop through that row n times, and then you can print out every string found in there using print(row[i])
Functions end as soon as a return is reached. You'll need to return once at the end instead of inside the loop:
def func1(x):
# The string to work on
new_str = ""
for (a,b) in enumerate (x):
# Add to the new string instead of returning immediately
if a%2 == 0:
new_str += b.upper()
else:
new_str += b.lower()
# Then return the complete string
return new_str
You are returning after first iteration.
Try the following:
def func1(x):
result = ''
for (a,b) in enumerate (x):
if a%2 == 0:
result += b.upper()
else:
result += b.lower()
return result
I have code that needs to run specifically in the first time in a loop and i'm wondering whats the best practice / pythonic way of wirting it.
Example:
for i in range(5):
if i == 0:
print("First")
print("normal execution")To skip the first element in Python you can simply write
for car in cars[1:]:
# Do What Ever you want
or to skip the last elem
for car in cars[:-1]:
# Do What Ever you want
You can use this concept for any sequence (not for any iterable though).
The other answers only work for a sequence.
For any iterable, to skip the first item:
itercars = iter(cars)
next(itercars)
for car in itercars:
# do work
If you want to skip the last, you could do:
itercars = iter(cars)
# add 'next(itercars)' here if you also want to skip the first
prev = next(itercars)
for car in itercars:
# do work on 'prev' not 'car'
# at end of loop:
prev = car
# now you can do whatever you want to do to the last one on 'prev'