Data Structures: Lists, Tuples, and Dictionaries
Welcome to our exploration of Python’s core data structures! In this lesson, we’ll compare Python’s lists, tuples, and dictionaries to their JavaScript counterparts. As a JavaScript developer, you’ll find many familiar concepts, but also some unique Python features that can make your code more expressive and efficient.
Lists vs. JavaScript Arrays
In Python, lists are similar to JavaScript arrays. They’re ordered, mutable sequences that can hold elements of different types.
# Python list
my_list = [1, "two", 3.0, [4, 5]]
# Accessing elements
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: [4, 5] (negative indexing)
# Modifying lists
my_list.append(6)
my_list.extend([7, 8])
my_list.insert(1, "inserted")
// JavaScript array
let myArray = [1, 'two', 3.0, [4, 5]];
// Accessing elements
console.log(myArray[0]); // Output: 1
console.log(myArray[myArray.length - 1]); // Output: [4, 5]
// Modifying arrays
myArray.push(6);
myArray.push(...[7, 8]);
myArray.splice(1, 0, 'inserted');
Python offers some unique ways to work with lists:
# List comprehension (as seen in the previous lesson)
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
# Slicing
print(my_list[1:4]) # Output: ['inserted', 'two', 3.0]
Tuples: Python’s Immutable Sequences
Tuples are unique to Python and have no direct equivalent in JavaScript. They’re immutable, ordered sequences:
my_tuple = (1, "two", 3.0)
# Accessing elements (similar to lists)
print(my_tuple[1]) # Output: "two"
# Trying to modify a tuple raises an error
# my_tuple[1] = "three" # TypeError: 'tuple' object does not support item assignment
# Tuples are often used for multiple return values
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(f"X: {x}, Y: {y}") # Output: X: 10, Y: 20
Dictionaries vs. JavaScript Objects
Python’s dictionaries are similar to JavaScript objects, but with some key differences:
# Python dictionary
my_dict = {
"name": "Alice",
"age": 30,
"skills": ["Python", "JavaScript"]
}
# Accessing values
print(my_dict["name"]) # Output: Alice
print(my_dict.get("height", "Not specified")) # Output: Not specified
# Modifying dictionaries
my_dict["location"] = "New York"
my_dict.update({"age": 31, "job": "Developer"})
# Getting all keys and values
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items()) # Returns a list of (key, value) tuples
// JavaScript object
let myObj = {
name: 'Alice',
age: 30,
skills: ['Python', 'JavaScript'],
};
// Accessing values
console.log(myObj.name); // Output: Alice
console.log(myObj.height || 'Not specified'); // Output: Not specified
// Modifying objects
myObj.location = 'New York';
Object.assign(myObj, { age: 31, job: 'Developer' });
// Getting all keys and values
console.log(Object.keys(myObj));
console.log(Object.values(myObj));
console.log(Object.entries(myObj)); // Returns an array of [key, value] pairs
Analogous to list comprehensions, Python offers dictionary comprehensions for creating dictionaries in a concise way:
# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Sets: Python’s Unordered Collections
In Python, sets are unordered collections of unique elements just like in JavaScript.
# Python
my_set = {1, 2, 3, 3, 4} # Duplicate values are automatically removed
print(my_set) # Output: {1, 2, 3, 4}
# Set operations
other_set = {3, 4, 5}
print(my_set.union(other_set)) # Output: {1, 2, 3, 4, 5}
print(my_set.intersection(other_set)) # Output: {3, 4}
// JavaScript
const mySet = new Set([1, 2, 3, 3, 4]); // Duplicate values are ignored
console.log(mySet); // Output: Set { 1, 2, 3, 4 }
// Set operations
const otherSet = new Set([3, 4, 5]);
// Union (added in ECMAScript 2024)
console.log(mySet.union(otherSet)); // Output: Set { 1, 2, 3, 4, 5 }
// Intersection (added in ECMAScript 2024)
console.log(mySet.intersection(otherSet)); // Output: Set { 3, 4 }
Conclusion
We’ve explored Python’s core data structures and how they compare to JavaScript’s arrays and objects. While there are similarities, Python’s unique features like tuples, list comprehensions, and set operations offer powerful tools for data manipulation.
In our next lesson, we’ll dive into Object-Oriented Programming in Python, exploring how classes and inheritance work compared to JavaScript’s prototypal inheritance model. Get ready to see how Python’s approach to OOP can enhance your coding toolkit!