() [] the difference between {} and where to use it

Asked 2 years ago, Updated 2 years ago, 19 views

I think people who study Python for the first time are confused, so I'll summarize it here. ()[]{} is used differently by type. I will explain it separately by type.

Array is a typical type of writing []. [] is used to declare and initialize an array, and to access elements in the array. Array does not write () or {}.

arr = [] #Use [] to create an empty array
arr = [1,2,3,4] #Use [] to create an array with elements

arr[3] #Use [] to approach the third element of the array

tuple is a typical type of writing (). () is used to declare and initialize a tuple. [] is used to access elements in a tuple. {} is not written.

mytuple = () #Use () to create an empty tuple
mytuple = (1,2,3,4) # Use () to make tuples with elements

mytuple[3] #Use [] to access the element of the tuple

You may feel that the tuple and dictionary are similar. A tuple cannot be removed or changed from an element that has already been created. On the other hand, an array can remove and change elements that have already been created. Also, tuples are usually used when the elements are of the same type. For example, tuples are usually used to store elements of the same type, such as (1,2,3,4), ("a", "b", "c"), and arrays are used to store different types, such as ["a", 3, [1,2,3]]. However, because this is Python's recommendation, storing various types in one tuple does not cause errors.

Dictionary is a typical type of writing {}. {} is used to declare and initialize dictionaries. [] is used to assign a value corresponding to the key, or to access the value.

mydictionary = {} #When creating an empty dictionary {}Use
mydictionary = {"mouse":3, "penguin":5}

Use to access the value (3) corresponding to mydictionary["mouse"] # key("mouse")
create value(1) for mydictionary["cat"] = 1 # key("cat")

python

2022-09-22 14:53

3 Answers

[Voiceover] Right.


2022-09-22 14:53

Thank you!


2022-09-22 14:53

I don't know the details, so I'll leave a question😅

Isn't the data type 1 not array but list type?


2022-09-22 14:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.