fbpx

Working with Sequences and Collections in Python

1. Sequences:

1.1 Strings:

Strings are sequences of characters and are immutable.

# Example of a string
message = "Hello, Python!"
  • Common Operations:
  • Concatenation: greeting = "Hello" + " " + "World"
  • Slicing: substring = message[7:13]
  • Methods: message.upper(), message.replace("Python", "GPT")

1.2 Lists:

Lists are mutable sequences that can store elements of different data types.

# Example of a list
fruits = ["apple", "banana", "orange"]
  • Common Operations:
  • Accessing Elements: first_fruit = fruits[0]
  • Slicing: sliced_fruits = fruits[1:3]
  • Appending: fruits.append("grape")
  • Removing: fruits.remove("banana")

1.3 Tuples:

Tuples are immutable sequences.

# Example of a tuple
coordinates = (3, 4)
  • Common Operations:
  • Accessing Elements: x = coordinates[0]
  • Unpacking: x, y = coordinates

2. Collections:

2.1 Sets:

Sets are unordered collections of unique elements.

# Example of a set
colors = {"red", "green", "blue"}
  • Common Operations:
  • Adding Elements: colors.add("yellow")
  • Removing Elements: colors.remove("green")
  • Set Operations: union_set = set1.union(set2), intersection_set = set1.intersection(set2)

2.2 Dictionaries:

Dictionaries are collections of key-value pairs.

# Example of a dictionary
person = {"name": "Alice", "age": 30, "city": "Wonderland"}
  • Common Operations:
  • Accessing Values: name = person["name"]
  • Adding and Updating Values: person["gender"] = "Female", person["age"] = 31
  • Removing Key-Value Pairs: del person["city"]

3. Iterating Through Sequences and Collections:

# Iterating through a list
for fruit in fruits:
    print(fruit)

# Iterating through a dictionary
for key, value in person.items():
    print(f"{key}: {value}")

4. List Comprehensions:

List comprehensions provide a concise way to create lists.

# Example of a list comprehension
squared_numbers = [x**2 for x in range(5)]

5. Functional Programming with map and filter:

# Using map to square each element in a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))

# Using filter to get even numbers from a list
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

6. Conclusion:

Understanding how to work with sequences and collections is essential for effective Python programming. Whether you’re manipulating strings, lists, tuples, sets, or dictionaries, Python provides a rich set of tools and techniques to handle diverse data structures.

In the next sections, we’ll explore more advanced topics and practical applications of sequences and collections in Python.