0

I am new to Python. I have the following nested list and I am adding items to the nested list with multiple append statements. How can I use just one append statement and a loop to append lists to the nested list?Suppose I have up to s100 (s1,s2,...s100) such individual lists which I would add to the nested list. My present code is given below:

s1= ["sea rescue","rescue boat", "boat"]
s2=["water quality","water pollution","water"]
nestedlist=[]    
nestedlist.append(s1)
nestedlist.append(s2)
print(nestedlist)

2 Answers 2

1

its a bad idea to use alot of variables in that way. Python have something fantastic for this. Dicts. You can use your variable name as keys and your list as values.

something like this:

foo = dict(s1= ["sea rescue","rescue boat", "boat"],
    s2 = ["water quality","water pollution","water"])

nestedlist= []

for bar in foo.values():

nestedlist.append(bar)

print(nestedlist)

This will save you alot of memory and code, wich in the end make you code easier to read. and the memory reference will also not be captured of 100 variables.

I strongly recommend you that, you actually learn dict becuse its a very important object in python.

I hope I answerd your question.

let me know if you have question

the output, will be a nested list like this:

[['sea rescue', 'rescue boat', 'boat'], ['water quality', 'water pollution', 'water']]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I will try it.
0

You can use the extend() method and you specify arguments in a list

here exemple using your code

s1= ["sea rescue","rescue boat", "boat"]
s2=["water quality","water pollution","water"]
nestedlist=[]    
nestedlist.extend([s1,s2])
print(nestedlist)

1 Comment

Thanks. I wish I could use something like s+loopvariable (=s1,s2..)

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.