Can you access a variable in Python before it is defined?

And if yes, how might we do this?

Could you add a little more detail? What do explicitly mean by 'before it is defined ’ ? Are you asking about the difference between declaring variables and defining them?

I was working on a personal project, here’s the snippet:

for element in range(4,len(spanish_formatted),5):
        spanish_formatted.insert(element,'\n')
count = sum([1 for thing in spanish_formatted])

I want to make it so I can use count replacing len(spanish_formatted.
I need my for loop to use the updated length of spanish_formatted and the variable count is equal to that length.
Problem is, count has to be defined after the for loop to give me the correct length.

I’m probably making 0 sense, and it’s fine if there isn’t a solution, I found an alternate solution a while ago, but still curious. I’m asking this question because I remembered hoisting in JS.

Ah sorry, I’m unfamiliar with JS but I can’t see how that would work. You could probably calculate count prior to the for loop but you’d still need len(spanish_formatted). Is count not effectively len() anyway? Built-in functions are generally much faster than any comprehension.

I think your best option there is to forgo .insert entirely. It is very slow as it has to rebuild the list. If it was originally a string ''.join('\n') with a sensible comprehension might be a good shout. It it is already a list then I’d actually suggest rebuilding the entire thing with a list comprehension with an if condition such as x % 5 to add the splits.

Could you elaborate on this? It sounds interesting.
It’s a list with strings inside of it.

Ah soz, was a little too vague on that one. When I mentioned if I meant the ternary conditional operator (or whatever it’s called in Python) might be a good way to do it (maybe not the best). If you needed the newlines as completely separate elements a function with append/extend may be a straightforward approach, i.e. no itertools.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

# rebuild but tags newlines onto letters (instead of extra element)
# could also be done by mutating the original list if that is acceptable
new_lst = [
    letter if idx % 5 else letter + '\n'
    for idx, letter in enumerate(lst, 1)
     ]
Out: ['a', 'b', 'c', 'd', 'e\n', 'f', 'g', 'h', 'i', 'j\n', 'k', 'l', 'm']

If you’re adding newlines for the sake of a prettier print it may be better to do so at the very end with some kind of formatting as opposed to actually building a new list.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.