0% found this document useful (0 votes)
30 views7 pages

Wa0005.

This document provides an overview of fundamental Python data structures including lists, dictionaries, tuples, and sets, along with their creation, operations, and built-in functions. It covers list operations such as indexing, slicing, and membership testing, as well as dictionary methods for accessing and modifying key-value pairs. Additionally, it explains the characteristics of tuples and sets, including their creation and common operations.

Uploaded by

rajumanjula226
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views7 pages

Wa0005.

This document provides an overview of fundamental Python data structures including lists, dictionaries, tuples, and sets, along with their creation, operations, and built-in functions. It covers list operations such as indexing, slicing, and membership testing, as well as dictionary methods for accessing and modifying key-value pairs. Additionally, it explains the characteristics of tuples and sets, including their creation and common operations.

Uploaded by

rajumanjula226
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Alright, let's dive into these fundamental Python data structures and object-oriented

programming concepts. Here are your notes, packed with information, syntax, and examples:

Lists
Creating Lists: Lists are ordered, mutable sequences of items. You can create them in several
ways:
●​ Using square brackets []:​
my_list = [1, 2, 3, 'hello', 3.14]​
empty_list = []​

●​ Using the list() constructor:​


another_list = list((10, 20, 30)) # From a tuple​
string_list = list("python") # From a string​

Operations on Lists:
●​ Accessing elements (indexing): Use square brackets with the index (0-based).
Negative indexing accesses elements from the end.​
my_list = [10, 20, 30, 40, 50]​
print(my_list[0]) # Output: 10​
print(my_list[-1]) # Output: 50​

●​ Slicing: Extract a sublist using [start:end:step].​


print(my_list[1:4]) # Output: [20, 30, 40]​
print(my_list[:3]) # Output: [10, 20, 30]​
print(my_list[::2]) # Output: [10, 30, 50]​

●​ Concatenation: Combine lists using the + operator.​


list1 = [1, 2]​
list2 = [3, 4]​
combined_list = list1 + list2​
print(combined_list) # Output: [1, 2, 3, 4]​

●​ Repetition: Repeat a list using the * operator.​


repeated_list = [0] * 5​
print(repeated_list) # Output: [0, 0, 0, 0, 0]​

●​ Membership testing: Check if an element exists using the in and not in operators.​
my_list = ['apple', 'banana', 'cherry']​
print('banana' in my_list) # Output: True​
print('grape' not in my_list) # Output: True​

Built-in Functions on Lists:


●​ len(list): Returns the number of elements in the list.​
my_list = [1, 2, 3, 4]​
print(len(my_list)) # Output: 4​
●​ max(list): Returns the largest element in the list (if elements are comparable).​
numbers = [10, 5, 20, 15]​
print(max(numbers)) # Output: 20​

●​ min(list): Returns the smallest element in the list (if elements are comparable).​
print(min(numbers)) # Output: 5​

●​ sum(list): Returns the sum of all elements in the list (if elements are numeric).​
print(sum(numbers)) # Output: 50​

●​ sorted(list): Returns a new sorted list without modifying the original.​


unsorted_list = [3, 1, 4, 1, 5, 9, 2, 6]​
sorted_list = sorted(unsorted_list)​
print(sorted_list) # Output: [1, 1, 2, 3, 4, 5, 6, 9]​
print(unsorted_list) # Output: [3, 1, 4, 1, 5, 9, 2, 6]​

Implementation of Stacks and Queues using Lists:


●​ Stack (LIFO - Last-In, First-Out): Lists can efficiently implement stacks using the
append() (push) and pop() methods.​
stack = []​
stack.append('a')​
stack.append('b')​
stack.append('c')​
print(stack) # Output: ['a', 'b', 'c']​
print(stack.pop()) # Output: 'c'​
print(stack) # Output: ['a', 'b']​
print(stack.pop()) # Output: 'b'​
print(stack) # Output: ['a']​

●​ Queue (FIFO - First-In, First-Out): For efficient queue implementation, it's better to use
collections.deque because pop(0) on a standard list is an O(n) operation. However, for
basic understanding:​
queue = []​
queue.append('first')​
queue.append('second')​
queue.append('third')​
print(queue) # Output: ['first', 'second', 'third']​
print(queue.pop(0)) # Output: 'first'​
print(queue) # Output: ['second', 'third']​
print(queue.pop(0)) # Output: 'second'​
print(queue) # Output: ['third']​

# More efficient using deque:​
from collections import deque​
efficient_queue = deque()​
efficient_queue.append('first')​
efficient_queue.append('second')​
efficient_queue.append('third')​
print(efficient_queue.popleft()) # Output: 'first'​

Nested Lists: Lists can contain other lists, creating nested structures (like matrices or
multi-dimensional arrays).
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]​
print(matrix[0]) # Output: [1, 2, 3]​
print(matrix[1][2]) # Output: 6 (element at row 1, column 2)​

Dictionaries
Creating Dictionaries: Dictionaries are unordered collections of key-value pairs. Keys must be
unique and immutable (strings, numbers, tuples).
●​ Using curly braces {}:​
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}​
empty_dict = {}​

●​ Using the dict() constructor:​


another_dict = dict(name='Bob', age=25, city='London')​
from_pairs = dict([('country', 'USA'), ('zip', '10001')])​

Operations on Dictionaries:
●​ Accessing values: Use the key in square brackets.​
print(my_dict['name']) # Output: Alice​
# Using .get() to avoid KeyError if the key doesn't exist​
print(my_dict.get('age')) # Output: 30​
print(my_dict.get('occupation')) # Output: None​
print(my_dict.get('occupation', 'Not specified')) # Output: Not
specified​

●​ Adding or modifying key-value pairs: Assign a value to a key.​


my_dict['occupation'] = 'Engineer' # Adding a new key-value pair​
my_dict['age'] = 31 # Modifying an existing value​
print(my_dict)​
# Output: {'name': 'Alice', 'age': 31, 'city': 'New York',
'occupation': 'Engineer'}​

●​ Deleting key-value pairs:


○​ del my_dict['city']: Deletes the entry with the specified key (raises KeyError if the
key doesn't exist).
○​ my_dict.pop('age'): Removes and returns the value associated with the key (can
take a default value as a second argument to avoid KeyError).
○​ my_dict.popitem(): Removes and returns the last inserted key-value pair (LIFO
order in Python 3.7+).
○​ my_dict.clear(): Removes all items from the dictionary.
Built-in Functions on Dictionaries:
●​ len(dict): Returns the number of key-value pairs.​
print(len(my_dict)) # Output (after additions/deletions): ...​

Dictionary Methods:
●​ keys(): Returns a view object that displays a list of all the keys in the dictionary.​
print(my_dict.keys()) # Output: dict_keys(['name', 'age',
'city'])​

●​ values(): Returns a view object that displays a list of all the values in the dictionary.​
print(my_dict.values()) # Output: dict_values(['Alice', 30, 'New
York'])​

●​ items(): Returns a view object that displays a list of all the key-value tuple pairs.​
print(my_dict.items()) # Output: dict_items([('name', 'Alice'),
('age', 30), ('city', 'New York')])​

●​ update(other_dict): Updates the dictionary with the key-value pairs from other_dict.
Existing keys are overwritten, new keys are added.​
more_info = {'country': 'USA', 'zip': '10001'}​
my_dict.update(more_info)​
print(my_dict)​
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001'}​

●​ setdefault(key, default): If the key is in the dictionary, it returns its value. If not, it inserts
the key with the specified default value and returns default.​
print(my_dict.setdefault('occupation', 'Not specified')) # Output:
Not specified​
print(my_dict)​
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001', 'occupation': 'Not specified'}​
print(my_dict.setdefault('age', 35)) # Key exists, returns
existing value​
print(my_dict)​
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001', 'occupation': 'Not specified'}​

Populating and Traversing Dictionaries:


●​ Populating: You can add key-value pairs directly or using methods like update() and
setdefault().
●​ Traversing: You can iterate through the keys, values, or key-value pairs using for loops.​
for key in my_dict: # Iterates through the keys​
print(key, my_dict[key])​

for value in my_dict.values(): # Iterates through the values​
print(value)​

for key, value in my_dict.items(): # Iterates through key-value
pairs​
print(f"Key: {key}, Value: {value}")​

Tuples and Sets


Creating Tuples: Tuples are ordered, immutable sequences of items.
●​ Using parentheses ():​
my_tuple = (1, 2, 3, 'hello', 3.14)​
empty_tuple = ()​
single_element_tuple = (5,) # Note the trailing comma​

●​ Using the tuple() constructor:​


another_tuple = tuple([10, 20, 30]) # From a list​
string_tuple = tuple("world") # From a string​

Operations on Tuples:
●​ Accessing elements (indexing): Similar to lists.​
print(my_tuple[0]) # Output: 1​
print(my_tuple[-1]) # Output: 3.14​

●​ Slicing: Similar to lists, creates a new tuple.​


print(my_tuple[1:4]) # Output: (2, 3, 'hello')​

●​ Concatenation: Use the + operator to create a new tuple.​


tuple1 = (1, 2)​
tuple2 = (3, 4)​
combined_tuple = tuple1 + tuple2​
print(combined_tuple) # Output: (1, 2, 3, 4)​

●​ Repetition: Use the * operator to create a new tuple.​


repeated_tuple = ('a',) * 3​
print(repeated_tuple) # Output: ('a', 'a', 'a')​

●​ Membership testing: in and not in operators work similarly to lists.


Built-in Functions on Tuples:
●​ len(tuple)
●​ max(tuple)
●​ min(tuple)
●​ sum(tuple)
●​ sorted(tuple): Returns a new sorted list from the tuple's elements.
Tuple Methods:
Tuples have fewer methods than lists due to their immutability:
●​ count(value): Returns the number of times a value appears in the tuple.​
my_tuple = (1, 2, 2, 3, 2)​
print(my_tuple.count(2)) # Output: 3​

●​ index(value): Returns the index of the first occurrence of a value. Raises ValueError if the
value is not found.​
print(my_tuple.index(3)) # Output: 3​

Creating Sets: Sets are unordered collections of unique elements.


●​ Using curly braces {}:​
my_set = {1, 2, 3, 3, 4} # Duplicate 3 is automatically removed​
empty_set = set() # Important: {} creates an empty
dictionary, not an empty set​

●​ Using the set() constructor:​


from_list = set([1, 2, 2, 3])​
from_string = set("hello") # Order is not guaranteed, duplicates
are removed​
print(from_string) # Output (order may vary): {'h', 'e', 'l',
'o'}​

Operations on Sets:
●​ Adding elements:
○​ set.add(element): Adds a single element.
○​ set.update(iterable): Adds multiple elements from an iterable (like a list or another
set).​
my_set = {1, 2, 3}​
my_set.add(4)​
print(my_set) # Output (order may vary): {1, 2, 3, 4}​
my_set.update([4, 5, 6])​
print(my_set) # Output (order may vary): {1, 2, 3, 4, 5,
6}​

●​ Removing elements:
○​ set.remove(element): Removes the specified element. Raises KeyError if the
element is not found.
○​ set.discard(element): Removes the element if it is present. Does not raise an error if
the element is not found.
○​ set.pop(): Removes and returns an arbitrary element from the set. Raises KeyError
if the set is empty.
○​ set.clear(): Removes all elements from the set.
●​ Set operations:
○​ Union (| or set.union(other_set)): Returns a new set containing all elements from
both sets.
○​ Intersection (& or set.intersection(other_set)): Returns a new set containing
elements common to both sets.
○​ Difference (- or set.difference(other_set)): Returns a new set containing
elements in the first set but not in the second.
○​ Symmetric Difference (^ or set.symmetric_difference(other_set)): Returns a
new set containing elements that are in either set, but not in both.
○​ Subset (<= or set.issubset(other_set)): Checks if all elements of the first set are
present in the second set.
○​ Superset (>= or set.issuperset(other_set)): Checks if all elements of the second
set are present in the first set.
set1 = {1, 2, 3, 4}​
set2 = {3, 4, 5, 6}​

print(set1 | set2) # Output (order may vary): {1, 2, 3,
4, 5, 6}​

You might also like