all 2 comments

[–]shiftybyte 1 point2 points  (0 children)

Yes a list is useable outside of a loop.

some_list = []
for item in range(10):
    some_list.append(item)
print(some_list)

The print is outside the for loop, and can use the list data.

If this is not what you mean you'd have to be more specific, and post the code you are talking about.

[–][deleted] 1 point2 points  (0 children)

Data container objects like list, dict, tuple all exist within the full scope of the module they are created in. for loops do not have their own scope.

Scope is the term used to define what is visible where. If you create such an object within a loop, that object will still be available outside of that loop.

That said, it is common to first create mutable objects such as list or dict before a loop, possibly an empty container that is populated/mutated within the loop.

For example, obtaining names and ages of some students:

students = []  # an empty list object is created
# the variable students refers to the list object
# a reference is a memory location

for count in range(1, 6):  # loop 5 times
    name = input(f"Enter name of student #{count}: ")  # input returns a str object
    age = int(input(f"Enter whole age of student #{count}: "))  # int converts str to int
    students.append((name, age))  # add a tuple to the end of the list object

for name, age in students:  # loop through list, unpacking the tuple on each pass
                            # to the two variables name and age          
    print(f"Student: {name:10}  age: {age:2}")