Differences between List, tuple, dict, and set in Python

python


1. list (List)

A list is an ordered, modifiable data type.

my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.append(6) # append 6 to the list
print(my_list)


2. tuple (Tuple)

A tuple is a data type that has an order, but cannot be modified once created.

It can be created by enclosing multiple values in curly brackets (()), or you can omit the curly brackets:

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
# my_tuple[0] = 100 # If you run this code, you will get an error. The tuple cannot be modified.


3. dict (Dict)

A dict is a data type that consists of keys and values, has no order and does not allow duplication of keys.

It is created using curly braces ({}), with each key and value separated by a colon (:).

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)
my_dict['age'] = 31 # Change the value corresponding to the 'age' key in the dictionary to 31
print(my_dict)

4. set (set)

A set is a data type that does not allow duplicates and has no order.

It is often used to remove duplicates or to check whether data exists.

It can be created using curly braces ({}) or by using the `set()` function:

my_set = {1, 2, 3, 4, 5}
print(my_set)
my_set.add(6) # add 6 to the set
print(my_set)
my_set.add(3) # 3 is not added because it already exists in the set.


Summary

1. list

Ordered, modifiable, [ ] type


2. tuple

Ordered, unmodifiable, ( ) type


3. dict

Composed of key and value, unordered, non-duplicate, { key : name } type


4. set

Composed of key and value only, unordered, non-duplicate, { } type




Reference

Reference

Apr 6, 2024 Views 83