Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

Python Data Structure

The document discusses Python data types including lists, tuples, sets, and dictionaries. It provides details on their definitions, characteristics, usage examples, and key operations and syntax in Python.

Uploaded by

myphotokingdom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Python Data Structure

The document discusses Python data types including lists, tuples, sets, and dictionaries. It provides details on their definitions, characteristics, usage examples, and key operations and syntax in Python.

Uploaded by

myphotokingdom
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Exploring Python Data Types: List, Tuple,

Set, and Dictionary


Lists Tuples
Ordered collection of elements Immutable sequence of elements

Sets Dictionaries
Unordered collection of unique elements Key-value pairs for data mapping

by Anudesh Saini
List
A list is a versatile collection of items, ordered and changeable. It allows duplicate elements, making it ideal for storing multiple similar
values. Lists are enclosed in square brackets [ ], and elements are separated by commas.

Key Points

Usage & Examples

A list can store heterogeneous data types and provides methods like append() and remove() for modification.

Differences from Other Data Types

A list differs from a tuple as it allows modifications, whereas a set has unique elements, and a dictionary stores key-value pairs.

List Creation
You can create a list in Python by enclosing elements in square brackets and separating them with commas. Here are some examples:

list_name = []: An empty list


list_name = [element1, element2, element3]: A list with elements
List Indexing
You can access individual elements of a list by their position using indexing. The index of the first element is 0. Here's an example:

list_name[index]: Access the element at the given index


List Slicing
Slicing a list allows you to extract a portion of the list by specifying the start and end indices. The syntax for list slicing is
list_name[start:end]. Here's an example:
list_name[start:end]: Extract a portion of the list from start to end (exclusive)
List Append
You can add an element to the end of a list using the append() method. Here's an example:
list_name.append(element): Add element to the end of the list
List Extend
extend() method. Here's an example:
You can extend a list by appending the elements of another list to it using the

list_name.extend(other_list): Append the elements of other_list to list_name


List Insert
insert() method. Here's an example:
You can insert an element at a specific index in a list using the

list_name.insert(index, element): Insert element at the given index


List Remove
You can remove the first occurrence of a specific element from a list using the remove() method. Here's an example:
list_name.remove(element): Remove the first occurrence of element from the list
List Pop
You can remove and return an element at a specific index from a list using the pop() method. Here's an example:
list_name.pop(index): Remove and return the element at the given index
List Concatenation
+ operator. Here's an example:
You can concatenate two lists using the

list_name1 + list_name2: Concatenate list_name1 and list_name2


List Length
You can determine the number of elements in a list using the len() function. Here's an example:
len(list_name): Return the length (number of elements) of the list.
Tuple
A tuple is an immutable collection of objects, ordered and indexed. It is declared using parentheses ( ) and separated by commas.
Tuples are commonly used for grouping related data together that shouldn't be changed.

Definition & Characteristics Usage & Examples


Tuples are immutable, meaning their values cannot be modified Tuples can be used as dictionary keys and are frequently used
or reassigned once created. to return multiple values from a function.

Creation of Tuple Different Applications of Tuple


Tuples can be created using parentheses and separating the Tuples have various applications, including:
values with commas. For example, my_tuple = (1, 2, 3) creates Storing related data as a single entity
a tuple with three elements.
Passing multiple values to functions
Indexing Returning multiple values from functions
Tuples are indexed starting from 0, so the first element can be Unpacking values
accessed using index 0, the second element with index 1, and so
Creating dictionaries with tuple keys
on. For example, my_tuple[0] returns the first element of the
tuple. Python Syntax

Concatenation Here are some examples of Python syntax related to tuples:

Tuples can be concatenated using the+ operator. For example, # Creation of Tuple
new_tuple = my_tuple + (4, 5) concatenates my_tuple with my_tuple = (1, 2, 3)
another tuple (4, 5).

Repetition # Indexing
first_element = my_tuple[0]
*
Tuples can be repeated using the operator. For example,
repeated_tuple = my_tuple * 3 repeats my_tuple three times. # Concatenation
new_tuple = my_tuple + (4, 5)
Slicing
:
Tuples can be sliced using the colon ( ) operator. For example, # Repetition
my_tuple[1:4] returns a new tuple containing elements from repeated_tuple = my_tuple * 3
index 1 to index 3.
# Slicing
Count sliced_tuple = my_tuple[1:4]
The count() method can be used to count the number of # Count
occurrences of a value in a tuple. For example,
count = my_tuple.count(2)
my_tuple.count(2) returns the count of occurrences of the
value 2 in the tuple.
Set
A set is an unordered collection of unique items. It is defined using curly braces { } or the set() constructor. Sets are often used for fast
membership testing and elimination of duplicate values.

Definition & Characteristics A set enforces uniqueness, ensuring each element appears
only once, and does not allow indexing.

Usage & Examples Sets are useful for finding common or distinct elements
between multiple sets using set operations like union(),
intersection(), and difference().

Python Syntax
Here are the key operations and syntax related to sets in Python:

Creation of Set: Sets can be created using curly braces { } or the set() constructor.

Adding Elements: Elements can be added to a set using the add() method or the |= operator.
Removal of Elements: Elements can be removed from a set using the remove() method or the -= operator.

Discard Element: The discard() method removes an element from a set if it is present, without raising an error if the element is not
found.
Intersection: The intersection() method or the & operator can be used to find the common elements between two sets.

Union: The union() method or the | operator can be used to find the union of two sets, i.e., all the unique elements from both sets.
Difference: The difference() method or the - operator can be used to find the elements that are present in one set but not in the
other.
Clear Set: The clear() method removes all elements from a set, making it an empty set.

Copy Set: The copy() method creates a shallow copy of a set.


Pop Element: The pop() method removes and returns an arbitrary element from a set.
Update Set: The update() method adds elements from another set or iterable to the current set.

Length of Set: The len() function can be used to get the number of elements in a set.
Dictionary
A dictionary is a collection of key-value pairs. It is enclosed in curly brackets { }, with each pair separated by a colon. Dictionaries are
mutable, unordered, and commonly used for data organization and efficient element retrieval.

Dictionaries are like glorified address books, where each entry (the key) is associated with specific information (the value).

1 Usage & Examples 2 Differences from Other Data Types


Dictionaries provide methods like items() for accessing Dictionaries differ from other data types as they are key-
elements, and they are often used in Python JSON parsing value pairs, allowing efficient lookup and retrieval.
and web scraping.

Python Syntax
Here are the key operations and syntax related to dictionaries in Python:

Creating a Dictionary: Dictionaries can be created using curly brackets { } or the dict() constructor.

Accessing Values: Values in a dictionary can be accessed using keys.

Modifying Values: Values in a dictionary can be modified by assigning a new value to the corresponding key.
Checking Key Existence: The `in` keyword can be used to check if a key exists in a dictionary.
Getting a Value: The `get()` method can be used to retrieve a value from a dictionary based on a key.

Length of Dictionary: The `len()` function can be used to get the number of key-value pairs in a dictionary.
Updating a Dictionary: The `update()` method can be used to add or update key-value pairs in a dictionary.

Sorting a Dictionary: Dictionaries are inherently unordered, but you can use the `sorted()` function to sort the dictionary based on
keys or values.

Hashing: Dictionaries are mutable and therefore not hashable.


Differences Between List, Tuple, Set, and
Dictionary
Data Type Order Mutable Indexed Unique Elements Key-Value Pairs

List Ordered Mutable Indexed Not Unique Not Key-Value

Tuple Ordered Immutable Indexed Not Unique Not Key-Value

Set Unordered Mutable Not Indexed Unique Not Key-Value

Dictionary Unordered Mutable Not Indexed Not Unique Key-Value


Interview Questions About Lists, Tuples,
Dictionaries, and Sets!
List:

1. Q: What is a list in Python? A: A list is a collection of ordered and mutable elements enclosed in square brackets, e.g., [1, 2, 3].
2. Q: How do you access elements in a list? A: You can access elements in a list using index notation, e.g., my_list[0] accesses the
first element.

3. Q: How do you add an element to a list? A: You can use the append() method to add an element to the end of a list.
4. Q: What is the difference between append() and extend() methods? A: append() adds its argument as a single element, while
extend() adds each element of its argument to the list.
5. Q: How do you remove an element from a list by value? A: You can use the remove() method to remove an element by its value.

Tuple:

1. Q: What is a tuple in Python? A: A tuple is an ordered, immutable collection of elements enclosed in parentheses, e.g., (1, 2, 3).
2. Q: How do you access elements in a tuple? A: You can access elements in a tuple using index notation, just like with lists.

3. Q: Can a tuple contain mutable elements? A: Yes, a tuple can contain mutable elements like lists, but the tuple itself is still
immutable.
4. Q: How do you swap the values of two variables using tuples? A: You can use tuple unpacking, e.g., (a, b) = (b, a).
Dictionary:

1. Q: What is a dictionary in Python? A: A dictionary is an unordered collection of key-value pairs enclosed in curly braces, e.g.,
{"name": "John", "age": 30}.
2. Q: How do you access values in a dictionary? A: You can access values by their keys, e.g., my_dict["name"] returns "John".
3. Q: How do you check if a key exists in a dictionary? A: You can use the in keyword or the get() method to check if a key exists.
4. Q: How can you add a new key-value pair to a dictionary? A: You can assign a value to a new key, e.g., my_dict["city"] = "New
York".
5. Q: How can you remove a key-value pair from a dictionary? A: You can use the pop() method to remove a key-value pair, or the del
statement.

Set:

1. Q: What is a set in Python? A: A set is an unordered collection of unique elements enclosed in curly braces, e.g., {1, 2, 3}.
2. Q: How do you add elements to a set? A: You can use the add() method to add a single element or the update() method to add
multiple elements.

3. Q: How do you remove elements from a set? A: You can use the remove() method or the discard() method to remove elements by
value.
4. Q: What is the difference between a set and a frozenset? A: A set is mutable, while a frozenset is immutable and cannot be
changed after creation.

5. Q: How do you find the union of two sets? A: You can use the union() method or the | operator to find the union of two sets.
6. Q: How do you find the intersection of two sets? A: You can use the intersection() method or the & operator to find the intersection
of two sets.

You might also like