Difference Between List, Tuple, Set, and Dictionary in Python

Difference Between List, Tuple, Set, and Dictionary in Python

Key Difference Between List, Tuple, Set, and Dictionary in Python

??Mutability:

  • Lists are mutable.
  • Tuples are immutable.
  • sets are mutable but do not allow modifying existing elements (only addition or removal).
  • dictionaries are mutable; keys are immutable, but values can change.

??Order:

  • List: Maintains order of elements.
  • Tuple: Maintains order of elements.
  • Set: (before Python 3.7) are unordered elements.
  • Dictionary: (before Python 3.7) are unordered elements.

??Uniqueness:

  • List: Allows duplicates.
  • Tuple: Allows duplicates.
  • Set: Not Allows duplicates.
  • Dictionary: keys are Not allowing duplicate; values can be duplicated.

??INDEXING:

List items are indexed, the first item has index [0], the second item has index [1] etc.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Set items are unindexed, it means that the elements in a set do not have a specific order or position, and therefore you cannot access elements using an index like you can with lists or tuples.

Dictionaries items are indexed, but Unlike lists and tuples, which are indexed by integer positions, dictionaries are indexed by their keys.

??Syntex:

  • List: Defined using square brackets [].
  • Tuple: Defined using parentheses ().
  • Set: Defined using curly braces {} or the set() function.
  • Dictionary: Defined using curly braces {} with key-value pairs separated by colons.

Let us know more about Lists, Tuples, Sets and Dictionaries in following topics:

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

LIST:

Lists are used to store multiple items in a single variable.

Lists allow duplicate values:

List Length

To determine how many items a list has, use the len() function:

List Items — Data Types

List items can be of any data type: A list with strings, integers and Boolean values

type()

From Python’s perspective, lists are defined as objects with the data type ‘list’:<class ‘list’>

List Indexing: List items are indexed, and you can access them by referring to the index number:

Note: The first item has index 0.

Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Note: The search will start at index 1 (included) and end at index 4 (not included).

Add List Items:

To add an item to the end of the list, use the append() method:

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Extend List

To append elements from another list to the current list, use the extend() method.

Remove List Items:

Remove Specified Item

The remove() method removes the specified item:

Remove Specified Index

The pop() method removes the specifid index

If you do not specify the index, the pop() method removes the last item.

Tuple: The Immutable Collection

Definition: Tuples are similar to lists but are immutable, meaning once a tuple is created, its elements cannot be changed.

Syntax: Created with parentheses ().

Features:

  • Index-based.
  • Allows duplicate elements.
  • Cannot be modified after creation (immutable).
  • Use Cases: When you need an ordered collection of items that should not change through the course of the program. Ideal for storing fixed data.

Tuple Items — Data Types:

Tuple items can be of any data type:String, int and boolean data types:

type()

<class ‘tuple’>

Update Tuples:

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

But there are some workarounds.

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Example:

Convert the tuple into a list to be able to change it:

Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:

Convert the tuple into a list, remove “apple”, and convert it back into a tuple:

Set: The Unique Element Collector

Definition: Sets are unordered collections of unique elements. They are mutable and do not allow duplicate elements.

Syntax: Created with curly braces {} or the set() function for an empty set.

Features:

  • Unordered, so elements cannot be accessed by index.
  • Automatically remove duplicate elements.
  • Elements can be added or removed.

Use Cases: When you need to ensure all elements are unique or when you need to perform set operations like union, intersection, difference, etc.

Note: the set list is unordered, meaning: the items will appear in a random order.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Note: The values True and 1 are considered the same value in sets, and are treated as duplicates:

Note: The values False and 0 are considered the same value in sets, and are treated as duplicates:

Set Items — Data Types

Set items can be of any data type:A set with strings, integers and boolean values:

type()

From Python’s perspective, sets are defined as objects with the data type ‘set’:

<class ‘set’>

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

Add Sets

To add items from another set into the current set, use the update() method


Dictionary: Key-Value Pairing

Definition: Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable, but values can be of any type and mutable.

Syntax: Created with curly braces {} with key-value pairs separated by colons :.

Features:

  • Key-value pairs allow direct access to values by keys.
  • Keys must be unique and immutable (e.g., strings, numbers, or tuples).
  • Values can be of any type and can be changed.
  • Elements can be added, removed, or changed.

Use Cases: When you need to associate keys with values, like looking up values by some identifier. Ideal for mappings or storing data in a way that makes it easily retrievable by its name or identifier.

  • In Python versions < 3.7: is an unordered collection of data.
  • In Python v3.1: a new type of dictionary called ‘OrderedDict’ was introduced, which was similar to dictionary in python; the difference was that orderedDict was ordered (as the name suggests)
  • In the latest version of Python, i.e. 3.7: Finally, in python 3.7, dictionary is now an ordered collection of key-value pairs. The order is now guaranteed in the insertion order, i.e. the order in which they were inserted.

Syntax & examples

Dictionary Items — Data Types

The values in dictionary items can be of any data type: String, int, Boolean, and list data types:

type()

From Python’s perspective, dictionaries are defined as objects with the data type ‘dict’:

<class ‘dict’>

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:


There is also a method called get() that will give you the same result:

Get Keys

The keys() method will return a list of all the keys in the dictionary.

Get Values

The values() method will return a list of all the values in the dictionary.

Get Items

The items() method will return each item in a dictionary, as tuples in a list.

Update Dictionary

The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key: value pairs.

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Removing Items

There are several methods to remove items from a dictionary:

The pop() method removes the item with the specified key name:

Adding Elements

  • Dictionary: Uses key-value pairs.
  • List: New items can be added using append() method.
  • Set: Uses add() method.
  • Tuple: Being immutable, new data cannot be added.

Deleting Elements

  • Dictionary: Uses pop(key) method to remove specified key and value.
  • List: Uses pop() method to delete an element.
  • Set: Uses pop() method to remove an element.
  • Tuple: Being immutable, no data can be popped or deleted.

Sorting Elements

  • Dictionary: Keys can be sorted using the sorted() method.
  • List: Uses sort() method to sort elements.
  • Set: Unordered, so sorting is not applicable.
  • Tuple: Being immutable, data cannot be sorted

Searching Elements

  • Dictionary: Uses the get(key) method to retrieve value for a specified key.
  • List: Uses index() method to search and return index of first occurrence.
  • Set: Unordered, so searching is not applicable.
  • Tuple: Uses index() method to search and return index of first occurrence.

Reversing Elements

  • Dictionary: No integer-based indexing, so no reversal.
  • List: Uses reverse() method to reverse elements.
  • Set: Unordered, so reversing is not advised.
  • Tuple: Being immutable, reverse method is not applicable.

Counting Elements

  • Dictionary: count() not defined for dictionaries.
  • List: Uses count() method to count occurrence of a specific element.
  • Set: count() is not defined for sets.
  • Tuple: Uses count() method to count occurrence of a specific element.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了