How to declare and add items to an array in Python?

前端 未结 7 604
轮回少年
轮回少年 2020-11-28 01:46

I\'m trying to add items to an array in python.

I run

array = {}

Then, I try to add something to this array by doing:



        
7条回答
  •  旧时难觅i
    2020-11-28 02:01

    In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:

    Java:

    int[] myIntArray = {1,2,3};
    String[] myStringArray = {"a","b","c"};
    

    However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}

    To actually define an array (which is actually called list in python) you can do:

    Python:

    mylist = [1,2,3]
    

    or other examples like:

    mylist = list()
    mylist.append(1)
    mylist.append(2)
    mylist.append(3)
    print(mylist)
    >>> [1,2,3]
    

提交回复
热议问题