Python Data Structures: Strings, Lists, Tuples, Dictionaries & Sets
1. What are strings in Python, and how do methods, formatting, and slicing work?
Q: What are strings?
Strings: Immutable sequences of Unicode characters (e.g., "hello", 'Python').
Properties: Enclosed in single ('), double ("), or triple quotes ('''/""" for multiline).
Methods: Common string methods include:
str.upper(),str.lower(): Convert to uppercase/lowercase.str.strip(): Remove leading/trailing whitespace.str.replace(old, new): Replace substrings.str.split(sep): Split into a list based on separator.str.join(iterable): Join iterable elements with string as separator.str.find(sub): Return index of first occurrence of sub or -1.
Formatting: Ways to format strings:
f-strings:f"Name: {name}"(Python 3.6+)..format():"Name: {}".format(name).% operator:"Name: %s" % name(older style).
Slicing: Extract substrings using [start:stop:step].
start: Starting index (inclusive).stop: Ending index (exclusive).step: Increment (default 1).
Use Case: Text processing, user input formatting, or substring extraction.
2. Can you give an example of strings, methods, formatting, and slicing?
# Strings: methods, formatting, slicing
text = " Hello, Python! "
# Methods
upper_text = text.upper()
stripped_text = text.strip()
replaced_text = text.replace("Python", "World")
words = text.split()
joined_text = "-".join(words)
# Formatting
name = "Krishna"
formatted = f"Welcome, {name}!"
formatted_old = "Welcome, {}!".format(name)
# Slicing
substring = text[2:7] # 'Hello'
reverse = text[::-1] # Reverse string
# Display results
print(f"Original: '{text}'")
print(f"Upper: '{upper_text}'")
print(f"Stripped: '{stripped_text}'")
print(f"Replaced: '{replaced_text}'")
print(f"Split: {words}")
print(f"Joined: '{joined_text}'")
print(f"f-string: '{formatted}'")
print(f"format(): '{formatted_old}'")
print(f"Sliced: '{substring}'")
print(f"Reversed: '{reverse}'")
Output:
Original: ' Hello, Python! '
Upper: ' HELLO, PYTHON! '
Stripped: 'Hello, Python!'
Replaced: ' Hello, World! '
Split: ['Hello,', 'Python!']
Joined: 'Hello,-Python!'
f-string: 'Welcome, Krishna!'
format(): 'Welcome, Krishna!'
Sliced: ' Hel'
Reversed: ' !nohtyP ,olleH '
Note:
- Demonstrates common string methods, f-strings, and slicing (including reverse with
::-1). - Strings are immutable; methods return new strings.
3. What are lists in Python, and how do methods and comprehensions work?
Q: What are lists?
Lists: Ordered, mutable sequences of elements (e.g., [1, 2, 3]).
Properties: Can contain mixed types, indexed (0-based), and modifiable.
Methods: Common list methods include:
list.append(x): Add x to the end.list.extend(iterable): Add elements from iterable.list.insert(i, x): Insert x at index i.list.remove(x): Remove first occurrence of x.list.pop(i): Remove and return element at index i (default: last).list.sort(): Sort in place.list.reverse(): Reverse in place.
Comprehensions: Concise way to create lists using a single line.
Syntax: [expression for item in iterable if condition].
Use Case: Storing collections, filtering data, or dynamic list manipulation.
4. Can you give an example of lists, methods, and comprehensions?
# Lists: methods and comprehensions
numbers = [1, 2, 3]
# Methods
numbers.append(4)
numbers.extend([5, 6])
numbers.insert(1, 1.5)
numbers.remove(2)
popped = numbers.pop()
numbers.sort()
numbers.reverse()
# Comprehensions
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in numbers if x % 2 == 0]
# Display results
print(f"After methods: {numbers}")
print(f"Popped value: {popped}")
print(f"Squares (comprehension): {squares}")
print(f"Evens (comprehension): {evens}")
Output:
After methods: [5.0, 3.0, 1.5, 1.0]
Popped value: 6
Squares (comprehension): [1, 4, 9, 16, 25]
Evens (comprehension): []
Note:
- Demonstrates list methods (
append,extend, etc.) and comprehensions for generating/filtering lists. - Lists are mutable; methods modify in place (except
pop()).
5. What are tuples in Python, and what operations are available?
Q: What are tuples?
Tuples: Ordered, immutable sequences of elements (e.g., (1, 2, 3)).
Properties: Fixed size, faster than lists, can contain mixed types.
Operations:
- Indexing/Slicing: Access elements with
[index]or[start:stop:step]. - Concatenation:
tuple1 + tuple2. - Repetition:
tuple * n. - Membership:
x in tuple. - Length:
len(tuple). - Count/Index:
tuple.count(x),tuple.index(x).
Use Case: Storing fixed data (e.g., coordinates, database records).
6. Can you give an example of tuples and operations?
# Tuples: operations
coords = (10, 20, 30)
# Operations
first = coords[0]
slice_tuple = coords[1:3]
concat = coords + (40, 50)
repeat = coords * 2
has_20 = 20 in coords
count_20 = coords.count(20)
index_30 = coords.index(30)
length = len(coords)
# Display results
print(f"Original tuple: {coords}")
print(f"First element: {first}")
print(f"Sliced: {slice_tuple}")
print(f"Concatenated: {concat}")
print(f"Repeated: {repeat}")
print(f"Contains 20: {has_20}")
print(f"Count of 20: {count_20}")
print(f"Index of 30: {index_30}")
print(f"Length: {length}")
Output:
Original tuple: (10, 20, 30)
First element: 10
Sliced: (20, 30)
Concatenated: (10, 20, 30, 40, 50)
Repeated: (10, 20, 30, 10, 20, 30)
Contains 20: True
Count of 20: 1
Index of 30: 2
Length: 3
Note:
- Tuples are immutable; operations like concatenation create new tuples.
- Useful for fixed data with low overhead.
7. What are dictionaries and sets in Python?
Q: What are dictionaries?
Dictionaries (dict) are mutable mappings of unique keys to values, with fast lookups.
Q: What are sets?
Sets (set) are mutable, unordered collections of unique elements, ideal for membership testing and mathematical operations.
Q: When to choose which data structure?
- List: Ordered, allows duplicates, mutable sequence.
- Tuple: Ordered, immutable, lightweight.
- Dict: Key-value pairs, fast lookup by key.
- Set: Unique elements, fast membership checks, set operations.
- String: Immutable text data.
Frequently asked questions
What are strings in Python?
Strings are immutable sequences of Unicode characters. They support methods like upper(), lower(), strip(), replace(), split(), join(), and operations like slicing and formatting (f-strings, .format()).
What are lists in Python?
Lists are ordered, mutable sequences that can hold mixed types. Common methods: append(), extend(), insert(), remove(), pop(), sort(), reverse(). List comprehensions provide concise creation and filtering.
What are tuples in Python?
Tuples are ordered, immutable sequences. Operations include indexing, slicing, concatenation (+), repetition (*), membership (in), count(), index(), and len().
What are dictionaries in Python?
Dictionaries are unordered (Python 3.7+ insertion-ordered), mutable mappings of unique keys to values. Support fast lookups, addition, deletion, and methods like keys(), values(), items().
What are sets in Python?
Sets are unordered, mutable collections of unique elements. Support mathematical operations: union (|), intersection (&), difference (-), symmetric difference (^).
When to use list vs tuple vs set vs dict in Python?
List: ordered, mutable, duplicates allowed. Tuple: ordered, immutable. Set: unique elements, fast membership testing. Dict: key-value mappings with unique keys.