kzs
kzs

Reputation: 1109

python appending to nested list with loop

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)

Upvotes: 0

Views: 295

Answers (2)

The.B
The.B

Reputation: 381

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']]

Upvotes: 1

Yefet
Yefet

Reputation: 2086

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)

Upvotes: 0

Related Questions