I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.
Here is a small example:
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
When I try a[0].insert(0, 1000)
for example, I'm met with an error. Is there any way to do this?
CodePudding user response:
You can use indexing to access the first sublist and then use the list.insert()
method to insert the new value at the specified index. For example:
a = ['Groceries', 'School Fees', 'Medicines', 'Furniture']
b = [[element] for element in a]
# Add the value 1000 to the first element of the first sublist
b[0].insert(0, 1000)
# The resulting nested list should be: [[1000, 'Groceries'], ['School Fees'], ['Medicines'], ['Furniture']]
print(b)
CodePudding user response:
Make a function for inner inserting.
Try this
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
def innerInsert(index, value):
try:
a[index].insert(index, value)
except AttributeError:
a[index] = []
a[index].insert(index, value)
innerInsert(0, 10000)
innerInsert(0, 100)
print(a)
[[100, 10000], 'School Fees', 'Medicines', 'Furniture']
For more options, I made some changes to the function
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
def innerInsert(l, iLstIndex, iLstValueIndex, value):
try:
l[iLstIndex].insert(iLstValueIndex, value)
except AttributeError:
l[iLstIndex] = []
l[iLstIndex].insert(iLstValueIndex, value)
innerInsert(a, 0, 0, 10000)
innerInsert(a, 0, 1, 2)
innerInsert(a, 0, 2, 3)
innerInsert(a, 0, 3, 4)
innerInsert(a, 0, 4, 1)
innerInsert(a, 0, 5, 2)
innerInsert(a[0], 4, 2, 100)
print(a)
OUTPUT
[[10000, 2, 3, 4, [100], 2], 'School Fees', 'Medicines', 'Furniture']