Reputation: 89
I have 5 lists containing data: List_1, List_2, List_3, List_4, List_5
I want to perform an analysis to each of these lists, but also keep the original lists as a reference for later so I can compare them. This is relatively easy to do since I only have 5 lists:
New_list_1 = List_1
New_list_2 = List_2
New_list_3 = List_3
New_list_4 = List_4
New_list_5 = List_5
I am aware that I could also make like a "list of lists" List = [List_1, List_2, List_3...]
but then I would still have the problem of having to do, which is not shorter:
New_list_1 = List[0]
New_list_2 = List[1]
New_list_3 = List[2]
New_list_4 = List[3]
New_list_5 = List[4]
But for future, what if I had like 700 lists? Would it be possible to loop over these numbered lists like this?
for i in range(700):
New_list_*insert i here somehow* = List_*insert i here somehow*
If this approach is possible, how would I go about attaching i
, which is an integer, as string, to a variable name?
Upvotes: -2
Views: 78
Reputation: 7
Here is your answer use this function and give the required value then it is gonna search for all of the lists in that namespace to create a copy of it.
def copy_all_lists(namespace):
"""
Finds all lists in the given namespace (e.g., globals() or locals()),
creates a copy of each list, and assigns the copy to a new variable
with the name `copy_<original_list_name>`.
Args:
namespace (dict): The namespace to search for lists (e.g., globals(), locals()).
"""
for name, value in namespace.items():
if isinstance(value, list):
# Create a copy of the list
namespace[f'copy_{name}'] = value.copy()
Here is an example of using this function
# Example usage
my_list = [1, 2, 3]
another_list = ['a', 'b', 'c']
print("Before copying:", globals())
# Call the function with globals() or locals() as the namespace
copy_all_lists(globals())
print("After copying:", globals())
Upvotes: -1
Reputation: 11
# Example of original lists (List_1, List_2, ..., List_5)
List_1 = [1, 2, 3]
List_2 = [4, 5, 6]
List_3 = [7, 8, 9]
List_4 = [10, 11, 12]
List_5 = [13, 14, 15]
# Put your original lists in a dictionary
lists = {
1: List_1,
2: List_2,
3: List_3,
4: List_4,
5: List_5
}
# If you have more lists, you can extend this dynamically or use a loop
# For example, simulating 700 lists (as an example)
for i in range(1, 701):
lists[f"New_list_{i}"] = lists[i].copy()
print(lists['New_list_1'])
Upvotes: 0
Reputation: 27196
If Lists is a list of lists then, to make a copy, you could do this:
Lists = [List_1, List_2, List_3, List_4, List_5]
New_lists = [e.copy() for e in Lists]
Note that a list's copy() function is shallow
Upvotes: 1