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:

Formatting: Ways to format strings:

Slicing: Extract substrings using [start:stop:step].

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:

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:

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:

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:

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:

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?

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.