Python lists, tuples, dictionaries

This time, I will explain the list, tuple, and dictionary of Python data types. This is the explanation of Python after a long time. Compare with Java declaration method and method.

list

A data type that represents a set of elements by maintaining the order of multiple elements. Declare by enclosing in []. If you want to set the elements at the time of declaration, declare the elements in [] separated by commas.

Access each element

Each element is accessible by index, and the index of list a of length n is 0..n-1. The mth (1 <= m <= n) element can be obtained with a [m -1].

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    print(a[1]) # ⇒ 1-2

Similarly in Java, the mth (1 <= m <= n) element can be obtained with a.get (m -1).

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    System.out.println(a.get(1)); // ⇒ 1-2;

Get size

To get the size of the list, use the len function.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    print(len(a)) # ⇒ 5

Java uses the size method.

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    System.out.println(a.size()); // ⇒ 5

Join list

Joining lists in python uses the + operator. This function joins the lists together to create a new list. Therefore, it does not affect the original list.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    b = ["2-1", "2-2", "2-3", "2-4", "2-5"]
    print(a + b) # ⇒ ['1-1', '1-2', '1-3', '1-4', '1-5', '2-1', '2-2', '2-3', '2-4', '2-5']
    print(a) # ⇒ ['1-1', '1-2', '1-3', '1-4', '1-5']
    print(b) # ⇒ ['2-1', '2-2', '2-3', '2-4', '2-5']

There doesn't seem to be a very good way in Java. It seems that I have no choice but to add all the elements a and b to the new list.

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    List<String> b = new ArrayList<String>(Arrays.asList(new String[]{"2-1", "2-2", "2-3", "2-4", "2-5"}));
    List<String> c = new ArrayList<String>();
    c.addAll(a);
    c.addAll(b);
    System.out.println(c); // ⇒ [1-1, 1-2, 1-3, 1-4, 1-5, 2-1, 2-2, 2-3, 2-4, 2-5]

Add an element to the list

There are two ways to add an element to a list: adding one element and adding one list to the whole list. First, to add one element, use the append and insert methods. append adds an element to the end of the list. insert adds an element at the specified index position.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    #Add it to the end of the list.
    a.append("1-7")
    print(a) # ⇒ ['1-1', '1-2', '1-3', '1-4', '1-5', '1-7']
    #Adds to the specified index location.
    a.insert(5, "1-6")
    print(a) # ⇒ ['1-1', '1-2', '1-3', '1-4', '1-5', '1-6', '1-7']

In Java, both use the add method.

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    a.add("1-7");
    System.out.println(a); // ⇒ [1-1, 1-2, 1-3, 1-4, 1-5, 1-7]
    a.add(5, "1-6");
    System.out.println(a); // ⇒ [1-1, 1-2, 1-3, 1-4, 1-5, 1-6, 1-7]

Then add one list to the whole list. Use the extend method. You can add all the elements of the list by specifying the list as an argument.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    b = ["2-1", "2-2", "2-3", "2-4", "2-5"]
    a.extend(b)
    print(a) # ⇒ ['1-1', '1-2', '1-3', '1-4', '1-5', '2-1', '2-2', '2-3', '2-4', '2-5']

I've already written it in Java, but you can add it by using the addAll method.

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    List<String> b = new ArrayList<String>(Arrays.asList(new String[]{"2-1", "2-2", "2-3", "2-4", "2-5"}));
    a.addAll(b);
    System.out.println(a); // ⇒ [1-1, 1-2, 1-3, 1-4, 1-5, 2-1, 2-2, 2-3, 2-4, 2-5]

Is the element included

Use "in" to see if an element is in the list. True is returned if it exists, False if it does not exist.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5", ["1-2", "1-3"]]
    print("1-2" in a) # ⇒ True
    print("1-6" in a) # ⇒ False
    #You can also check if the list exists in the list as follows.
    print(["1-2", "1-3"] in a) # ⇒ True

Java uses the contains method.

Java


    a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    System.out.println(a.contains("1-2")); // ⇒ true
    System.out.println(a.contains("1-6")); // ⇒ false

Cut out elements

To cut out an element, specify it in the format of [n: m] like a character string.

Python


    a = ["1-1", "1-2", "1-3", "1-4", "1-5"]
    #Index 2 to index 4 (4 not included)
    print(a[2:4]) # ⇒ ['1-3', '1-4']
    #Index 2 to the end
    print(a[2:]) # ⇒ ['1-3', '1-4', '1-5']
    #Up to index 4 (4 not included)
    print(a[:4]) # ⇒ ['1-1', '1-2', '1-3', '1-4']
    #Get every two
    print(a[::2]) # ⇒ ['1-1', '1-3', '1-5']

Java uses the subList method. The arguments are the cut start index and end index (not included).

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    //Index 2 to index 4 (4 not included)
    System.out.println(a.subList(2, 4)); // ⇒ [1-3, 1-4]
    //Index 2 to the end
    System.out.println(a.subList(2, a.size())); // ⇒ [1-3, 1-4, 1-5]
    //Up to index 4 (4 not included)
    System.out.println(a.subList(0, 4)); // ⇒ [1-1, 1-2, 1-3, 1-4]
    //Is it impossible to get every two unless Filter is applied with Stream?

Tuple

Next, I will explain tuples. Tuples are lists whose contents cannot be changed. Therefore, using a method that modifies an element that is not a tuple will result in an error. Unless you change it, no error will occur. It is also possible to add the tuple itself to the list.

Python


    a = ("1-1", "1-2", "1-3", "1-4", "1-5")
    a.append("1-6") # ⇒ AttributeError: 'tuple' object has no attribute 'append'
    c = ["1-1"];
    c.extend(a)
    print(c) # ⇒ ['1-1', '1-1', '1-2', '1-3', '1-4', '1-5']

Lists that cannot be modified in Java can be created using Collections.unmodifiableList. Of course, you can create your own class. You can also create an immutable Map in the Collections class, so if you have time, you can take a look.

Java


    List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"1-1", "1-2", "1-3", "1-4", "1-5"}));
    List<String> unmodifList = Collections.unmodifiableList(a);
    unmodifList.add("1-1"); // ⇒ UnsupportedOperationException

dictionary

Like a list, it is a collection type, but unlike a list, it has no order. Instead, it manages the value by the key and the corresponding value. The declaration method is to enclose it in curly braces ({}) and declare key and value separated by a colon (:). Separate them with commas (,) to declare the following values.

Python


    a = {"key" : "value", "A" : "13 years old", "B" : "15 years old"}
    print(a) # ⇒ {'key': 'value', 'A': '13 years old', 'B': '15 years old'}

It's a map in Java. There is no way to set the initial value in Java Map.

Java


    Map<String, String> map = new HashMap<String, String>();
    System.out.println(map); // ⇒{}

Add element

There is no method to add an element to the dictionary type. Directly specify the key and value to add to the dictionary type variable.

Python


    a = {"key" : "value", "A" : "13 years old", "B" : "15 years old"}
    a["C"] = "16 years old"
    print(a)  # ⇒ {'key': 'value', 'A': '13 years old', 'B': '15 years old', 'C': '16 years old'}

Java uses the put method.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    map.put("C", "16 years old");
    System.out.println(map); // ⇒{A=13 years old, B=15 years old, C=16 years old}

Does the key exist

Use "in" to check if a key exists in a dictionary variable.

Python


    a = {"key" : "value", "A" : "13 years old", "B" : "15 years old"}
    print("A" in a)  # ⇒ True
    print("C" in a)  # ⇒ False

Java uses the containsKey method. There is also a containsValue method that allows you to check if it is included in Value other than the key. There seems to be no method corresponding to containsValue in python.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    System.out.println(map.containsKey("A")); // ⇒ true
    System.out.println(map.containsKey("C")); // ⇒ false
    System.out.println(map.containsValue("15 years old")); // ⇒ true
    System.out.println(map.containsValue("16 years old")); // ⇒ false

Get value

Use the get method to get the value. The get method specifies the key and gets the Value value. If the key does not exist, None will be returned. If the key doesn't exist, you may find it difficult to return None. In that case, set the default value in the second argument of get. Then, if the key value exists, the specified default value is returned.

Python


    a = {"key" : "value", "A" : "13 years old", "B" : "15 years old"}
    print(a.get("A"))  #⇒ 13 years old
    print(a.get("C"))  # ⇒ None
    print(a.get("A", "10 years old"))  #⇒ 13 years old
    print(a.get("C", "10 years old"))  # ⇒ 10 years old

Java also uses the get method to get the value corresponding to the key. Also, if you want to set the default value and get it, use the getOrDefault method. Usage is the same as specifying the default value for python. This method was added from Java 8. Thank you for being sober.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    System.out.println(map.get("A")); //⇒ 13 years old
    System.out.println(map.get("C")); // ⇒ null
    System.out.println(map.getOrDefault("A", "10 years old")); //⇒ 13 years old
    System.out.println(map.getOrDefault("C", "10 years old")); // ⇒ null

Get all keys

If you want to get all the keys registered in the dictionary, use the keys method. The registered key will be returned in a list format. However, the order is not guaranteed. I thought, but a class called dict_keys was returned. To take advantage of this, you have to use a for statement.

Python


    a = {"A" : "13 years old", "B" : "15 years old"}
    print(a.keys())  # ⇒ dict_keys(['A', 'B'])
    for key in a.keys():
        print(key)# ⇒ 'A'When'B'

In java, use the keySet method. This method returns the key set in the Set class.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    System.out.println(map.keySet()); // ⇒ [A, B]
    for (String s : map.keySet()) {
        System.out.println(s); // ⇒ A, B
    }

Get all values

If you want to get the values registered in the dictionary, use the values method. A class called dict_values will be returned. To take advantage of this, you have to use a for statement.

Python


    a = {"A" : "13 years old", "B" : "15 years old"}
    print(a.values())  # ⇒ dict_values(['13 years old', '15 years old'])
    for value in a.values():
        print(value) # ⇒ '13 years old'When'15 years old'

In java, use the keySet method. This method returns the key set in the Set class.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    System.out.println(map.values()); // ⇒ [13 years old,15 years old]
    for (String s : map.values()) {
        System.out.println(s); //⇒ 13 years old,15 years old
    }

Get all keys and values

If you want to get the key and value registered in the dictionary, use the items method. A class called dict_items will be returned. To take advantage of this, you have to use a for statement.

Python


    a = {"A" : "13 years old", "B" : "15 years old"}
    print(a.items())  # ⇒ dict_items([('A', '13 years old'), ('B', '15 years old')])
    for key, value in a.items():
        print(key, value) #⇒ A 13 years old,B 15 years old

In java, use the entrySet method. This method returns a key and value Entry in the Set class.

Java


    Map<String, String> map = new HashMap<String, String>();
    map.put("A", "13 years old");
    map.put("B", "15 years old");
    System.out.println(map.entrySet()); // ⇒ [A=13 years old, B=15 years old]
    for (Entry<String, String> e : map.entrySet()) {
        System.out.println(e.getKey()); // ⇒ A, B
        System.out.println(e.getValue()); //⇒ 13 years old,15 years old
    }

Dictionary supplement

It seems that the objects returned by values (), keys (), items () are view objects. The view object provides a dynamic view of the items in the dictionary, but it seems that the value of the view changes as the value of the original dictionary changes.

Python


a = {"A" : "13 years old", "B" : "15 years old"}
items = a.items()
print(items) # ⇒ dict_items([('A', '13 years old'), ('B', '15 years old')])
#If you add an element, the view object will have more elements
a["C"] = "16 years old"
print(items) # ⇒ dict_items([('A', '13 years old'), ('B', '15 years old'), ('C', '16 years old')])
#If you delete an element, the view object element also disappears
a.pop("A")
print(items) # ⇒ dict_items([('B', '15 years old'), ('C', '16 years old')])
#If you change the element, the element of the view object also changes
a["B"] = "14 years old"
print(items) # ⇒ dict_items([('B', '14 years old'), ('C', '16 years old')])

that's all. Overall, I think Python is easier to write.

Recommended Posts

Python3 | Lists, Tuples, Dictionaries
Python lists, tuples, dictionaries
Python> Tuples versus Lists
Save lists, dictionaries and tuples to external files python
Understand python lists, dictionaries, and so on.
[Introduction to Python3 Day 7] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.3-3.8)
[Introduction to Python3 Day 5] Chapter 3 Py Tools: Lists, Tuples, Dictionaries, Sets (3.1-3.2.6)
[Introduction to Python3 Day 6] Chapter 3 Py tool lists, tuples, dictionaries, sets (3.2.7-3.2.19)
How to use lists, tuples, dictionaries, and sets
Memorize Python commentary 5 --Lists
[Short sentence] [Python] Format and print lists and dictionaries
How tuples work | Python
Manipulating Python character lists (arrays)
Python Basic Course (5 List Tuples)
Python list and tuples and commas
Paiza Python Primer 5: Basics of Dictionaries
What's new in python3.9 Merge dictionaries
Python
Find memory-consuming lists / arrays on Python
Easily handle lists with python + sqlite3
Make Python dictionaries accessible as attributes
I'm addicted to Python 2D lists
Mixed positional arguments, tuples and dictionaries
[Python] Chapter 04-06 Various data structures (creating dictionaries)
Alternative: Make Python dictionaries accessible as attributes
Manipulating Python character lists (arrays)
[Python beginner] Join two lists alternately (5 lines).
Process multiple lists with for in Python