-2

I have a value that creates a list with two values. I need to add it as a sublist to another list muptiple times.

I need the resulting list to look like this: [["a", 1], ["b", 2], ["c", 3], ["d", 4]]

So this:

Small_list = []
Big_list = []
for item in db[1:]:
   Small_list.append(item)
   for item2 in db[2:]:
      Small_list.append(item2)
      Big list.append()
print(Big_list)

Returns: [[], [], [], []]

But doing the .extend() method

Small_list = []
Big_list = []
for item in db[1:]:
   Small_list.append(item)
   for item2 in db[2:]:
      Small_list.append(item2)
      Big list.extend()
print(Big_list)

Returns: ["a", 1, "b", 2, "c", 3, "d", 4]

Why does this happen and how do I do it the right way?

3
  • Are you sure your two examples are actually exactly what you are running? In both cases, nothing should be getting added into Big_list as both the append and extend list methods require you to pass them values, which is not being done in either or your cases. Commented Dec 13, 2024 at 10:52
  • Please also provide information on what db contains, so that your question is reproducible. Commented Dec 13, 2024 at 10:55
  • It's a list of lists containing data from google spreadsheets through gspread's worksheet.get_all_values() Commented Dec 13, 2024 at 11:23

1 Answer 1

0

The Small_list is not getting reset.

The .extend() adds content to the end of the list.

In order for this to work:

  1. Create a new Small_list for every pair of values.
  2. Append the Small_list to Big_list.

Example Code:

db = ["a", 1, "b", 2, "c", 3, "d", 4]  # Example data
Big_list = []

# Assuming `db` contains alternating elements (key-value pairs)
for i in range(0, len(db), 2):  # Step by 2 to process pairs
    Small_list = [db[i], db[i + 1]]  # Create a new sublist for each pair
    Big_list.append(Small_list)  # Add the sublist to the big list

print(Big_list)
Sign up to request clarification or add additional context in comments.

4 Comments

My fault, I forgot to mention that I do Small_list.clear() at the end of the second for loop I'm just curious as to why it doesn't pass any values within lists, while a "print" would show [a, 1], [b, 2] and so on for every loop
Oh, and db itself contains a list of lists, it's just rows from a google spreadsheet basically
When you call Small_list.clear(), you're emptying the same list object that Big_list references.
What does your db look like?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.