Crip
Crip

Reputation: 1

Adding lists to a list

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?

Upvotes: -1

Views: 26

Answers (1)

Snoke
Snoke

Reputation: 105

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)

Upvotes: 0

Related Questions