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?
Crip is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
The Small_list
is not getting reset.
The .extend()
adds content to the end of the list.
In order for this to work:
- Create a new
Small_list
for every pair of values. - Append the
Small_list
toBig_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)
4