close

How to add an element to a list?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to add an element to a list in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to add an element to a list?

  1. How to add an element to a list?

    I would do this:
    data["list"].append({'b':'2'})
    so simply you are adding an object to the list that is present in “data”

  2. add an element to a list

    I would do this:
    data["list"].append({'b':'2'})
    so simply you are adding an object to the list that is present in “data”

Method 1

I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in “data”

Method 2

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read