Sunday 7 January 2024

Difference between Lists and sets in Python

 Lists and sets in Python are both used for storing collections of elements, but they have several differences based on their characteristics and use cases. Here are some key differences between lists and sets in Python:

Ordering:

Lists: Maintain the order of elements. The order in which elements are added is preserved, and you can access elements by their index.

Sets: Do not maintain any specific order. The elements are unordered, and you cannot access them by index.

Uniqueness:

Lists: Allow duplicate elements. You can have the same value multiple times in a list.

Sets: Enforce uniqueness. Each element in a set must be unique; duplicates are automatically removed.

Declaration:

Lists: Created using square brackets [].

Sets: Created using curly braces {} or the set() constructor.

Mutability:

Lists: Mutable, meaning you can change the elements after the list is created. You can add, remove, or modify elements.

Sets: Mutable, but individual elements cannot be modified once the set is created. You can add and remove elements, but you can't change them.

Indexing:

Lists: Allow indexing and slicing. You can access elements by their position in the list.

Sets: Do not support indexing or slicing. Elements cannot be accessed by position.

Here's a brief example illustrating some of these differences:


# Lists

my_list = [1, 2, 3, 3, 4, 5]

print(my_list)        # Output: [1, 2, 3, 3, 4, 5]

print(my_list[2])     # Output: 3


# Sets

my_set = {1, 2, 3, 3, 4, 5}

print(my_set)         # Output: {1, 2, 3, 4, 5}

# print(my_set[2])    # Raises TypeError, sets do not support indexing

In the above example, the list allows duplicates and supports indexing, while the set automatically removes duplicates and does not support indexing. Choose between lists and sets based on your specific requirements for ordering, uniqueness, and mutability.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (752) Python Coding Challenge (226) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses