Skip to main content

Command Palette

Search for a command to run...

The JavaScript Developer's Guide to Learning Python - PART 2

Updated
•26 min read•View as Markdown

🐍 Strings in Python: A JavaScript Developer's Guide

Strings are everywhere in AI. Whether you're building chatbots, processing documents, cleaning datasets, or interacting with Large Language Models (LLMs), almost everything starts as text. Before diving into AI libraries, it's important to become comfortable working with strings in Python.


What is a String?

A string is a sequence of characters used to store text.

Strings can contain:

  • Letters

  • Numbers

  • Symbols

  • Spaces

In Python, strings can be created using either single quotes or double quotes.

name = "Aditya"

city = 'Varanasi'

Both are completely valid.

Unlike JavaScript, Python developers don't have to worry much about choosing between single and double quotes.


String Indexing

Every character inside a string has a position called an index.

Python starts counting from 0.

H  e  l  l  o

0  1  2  3  4

Example

text = "Hello"

print(text[0])

print(text[1])

print(text[4])

Output

H
e
o

Python also supports negative indexing.

H  e  l  l  o

-5 -4 -3 -2 -1
text = "Hello"

print(text[-1])

print(text[-2])

Output

o
l

Negative indexing is extremely useful when you want to access characters from the end of a string.

💡 JavaScript Comparison

JavaScript also supports indexing using string[index], so this should feel familiar.


String Slicing

Instead of accessing one character, you can extract multiple characters using slicing.

Syntax

string[start:stop]

Example

text = "Artificial Intelligence"

print(text[0:10])

print(text[11:23])

Output

Artificial
Intelligence

The start index is included, while the stop index is excluded.

You can also omit values.

text = "Python"

print(text[:3])

print(text[2:])

print(text[:])

Output

Pyt
thon
Python

You can even use steps.

text = "Python"

print(text[::2])

Output

Pto

Common String Methods

Python provides many built-in methods for manipulating strings.


Convert to Uppercase

text = "python"

print(text.upper())

Output

PYTHON

Convert to Lowercase

text = "PYTHON"

print(text.lower())

Output

python

Remove Extra Spaces

text = "   AI Engineer   "

print(text.strip())

Output

AI Engineer

Replace Text

text = "Hello World"

print(text.replace("World", "Python"))

Output

Hello Python

Split a String

skills = "Python,JavaScript,SQL"

print(skills.split(","))

Output

['Python', 'JavaScript', 'SQL']

Join Strings

skills = ["Python", "JavaScript", "SQL"]

print(", ".join(skills))

Output

Python, JavaScript, SQL

Check if a String Starts or Ends With Something

filename = "resume.pdf"

print(filename.endswith(".pdf"))

print(filename.startswith("resume"))

Output

True
True

String Formatting with f-Strings

One of Python's best features is f-strings.

Instead of manually concatenating strings, Python lets you embed variables directly.

name = "Aditya"

age = 22

print(f"My name is {name} and I am {age} years old.")

Output

My name is Aditya and I am 22 years old.

JavaScript Comparison

JavaScript

const name = "Aditya";
const age = 22;

console.log(`My name is ${name} and I am ${age} years old.`);

Python

print(f"My name is {name} and I am {age} years old.")

If you've used JavaScript template literals, Python's f-strings will feel very natural.


🤖 Why Strings Matter for AI

Almost everything in modern AI revolves around text.

Strings are used to:

  • Writing prompts for LLMs

  • Cleaning datasets

  • Processing documents

  • Tokenization

  • Chatbot conversations

  • Reading files

  • Calling APIs

  • Parsing JSON responses

Mastering strings is one of the most valuable Python skills for AI engineers.


JavaScript vs Python

JavaScript Python
str[0] str[0]
substring() Slicing [:]
toUpperCase() upper()
toLowerCase() lower()
replace() replace()
split() split()
join() " ".join()
Template Literals f-Strings

Common Beginner Mistakes

❌ Strings are immutable.

text = "Python"

text[0] = "J"

This raises an error.

✅ Correct

text = text.replace("P", "J")

Key Takeaways

✅ Strings are sequences of characters.

✅ Python supports both positive and negative indexing.

✅ Slicing extracts parts of a string.

✅ Built-in methods simplify text manipulation.

✅ f-strings provide a clean and readable way to format text.


Final Thoughts

Strings are one of the most important data types in Python, especially if you're learning AI. From writing prompts to preprocessing datasets and handling model responses, you'll be working with text constantly.

The more comfortable you become with string operations, the easier it will be to build real-world AI applications.

In the next article, we'll explore Lists in Python, one of the most versatile and frequently used data structures for storing and manipulating collections of data.


🐍 Lists in Python: A JavaScript Developer's Guide

Lists are one of Python's most versatile data structures. Whether you're storing user inputs, model predictions, datasets, or API responses, you'll use lists constantly. If you're coming from JavaScript, you can think of lists as Python's version of arrays—with some powerful built-in features.


What is a List?

A list is an ordered collection of items.

A list can store:

  • Numbers

  • Strings

  • Booleans

  • Other lists

  • Even different data types together

Creating a list is simple.

fruits = ["Apple", "Banana", "Mango"]

numbers = [10, 20, 30, 40]

mixed = [1, "Python", True, 3.14]

Unlike some programming languages, Python lists can hold different data types in the same collection.

💡 JavaScript Comparison

If you've worked with JavaScript, Python lists are very similar to JavaScript arrays.


List Indexing

Every element has an index.

Python starts indexing from 0.

Apple   Banana   Mango

0         1        2

Example

fruits = ["Apple", "Banana", "Mango"]

print(fruits[0])

print(fruits[2])

Output

Apple
Mango

Negative indexing also works.

print(fruits[-1])

print(fruits[-2])

Output

Mango
Banana

List Slicing

Slicing allows us to extract multiple elements.

Syntax

list[start:stop]

Example

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

print(numbers[:3])

print(numbers[2:])

Output

[20, 30, 40]

[10, 20, 30]

[30, 40, 50]

You can also use steps.

print(numbers[::2])

Output

[10, 30, 50]

Adding Elements

append()

Adds an item to the end of the list.

fruits = ["Apple", "Banana"]

fruits.append("Mango")

print(fruits)

Output

['Apple', 'Banana', 'Mango']

insert()

Adds an element at a specific index.

fruits.insert(1, "Orange")

print(fruits)

Output

['Apple', 'Orange', 'Banana', 'Mango']

extend()

Adds multiple elements.

fruits.extend(["Kiwi", "Grapes"])

print(fruits)

Output

['Apple', 'Orange', 'Banana', 'Mango', 'Kiwi', 'Grapes']

Removing Elements

remove()

Removes a specific value.

fruits.remove("Orange")

print(fruits)

pop()

Removes an element by index.

fruits.pop()

print(fruits)

If no index is provided, the last element is removed.


del

Deletes an element or even the whole list.

del fruits[0]

print(fruits)

clear()

Removes everything.

fruits.clear()

print(fruits)

Output

[]

Common List Methods

length

numbers = [10, 20, 30]

print(len(numbers))

Output

3

sort()

numbers = [5, 2, 8, 1]

numbers.sort()

print(numbers)

Output

[1, 2, 5, 8]

reverse()

numbers.reverse()

print(numbers)

Output

[8, 5, 2, 1]

count()

numbers = [1, 2, 1, 3, 1]

print(numbers.count(1))

Output

3

index()

fruits = ["Apple", "Banana", "Mango"]

print(fruits.index("Banana"))

Output

1

Nested Lists

A list can contain another list.

matrix = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

]

Accessing values

print(matrix[1][2])

Output

6

The first index selects the row.

The second index selects the column.


🤖 Why Nested Lists Matter for AI

Many AI concepts rely on nested lists.

For example:

  • Images are represented as matrices.

  • Machine learning datasets contain rows and columns.

  • Neural network weights are stored in multi-dimensional structures.

  • Before learning NumPy, understanding nested lists makes everything easier.


JavaScript vs Python

JavaScript Python
Array List
push() append()
unshift() insert()
pop() pop()
length len()
splice() insert() / remove()
Nested Arrays Nested Lists

Common Beginner Mistakes

❌ Confusing append() and extend().

numbers = [1, 2]

numbers.append([3, 4])

print(numbers)

Output

[1, 2, [3, 4]]

✅ Correct

numbers.extend([3, 4])

print(numbers)

Output

[1, 2, 3, 4]

Key Takeaways

✅ Lists are ordered and mutable.

✅ Python supports positive and negative indexing.

✅ Slicing makes extracting data simple.

✅ Built-in methods make adding and removing items easy.

✅ Nested lists are the foundation of many AI data structures.


Final Thoughts

Lists are one of the most frequently used data structures in Python. From storing datasets to handling API responses and preparing training data, you'll encounter them in almost every AI project.

Mastering lists now will make it much easier to work with libraries like NumPy and Pandas later in your AI journey.

In the next article, we'll explore Tuples and Sets, understanding when to use each and how they differ from lists.


Dictionaries in Python

Dictionaries are one of Python's most powerful and frequently used data structures. If lists store values using indexes, dictionaries store values using unique keys. You'll encounter dictionaries everywhere—from API responses and configuration files to AI model outputs and JSON data.


What is a Dictionary?

A dictionary is an unordered collection of key-value pairs.

Each key is unique and is used to access its corresponding value.

Think of it as a real-world dictionary:

  • The word is the key.

  • The meaning is the value.

In Python, dictionaries are created using curly braces {}.

student = {
    "name": "Aditya",
    "age": 22,
    "course": "AI Engineering"
}

Here,

  • "name" is the key.

  • "Aditya" is the value.

Unlike lists, dictionaries don't use numeric indexes. Instead, they retrieve data using keys.


JavaScript Comparison

If you're familiar with JavaScript, Python dictionaries are very similar to JavaScript objects.

JavaScript

const student = {
    name: "Aditya",
    age: 22,
    course: "AI Engineering"
};

Python

student = {
    "name": "Aditya",
    "age": 22,
    "course": "AI Engineering"
}

The concept is nearly identical—the syntax is slightly different.


Accessing Values

Values are accessed using their keys.

student = {
    "name": "Aditya",
    "age": 22,
    "course": "AI Engineering"
}

print(student["name"])
print(student["age"])

Output

Aditya
22

You can also use the get() method.

print(student.get("course"))

Output

AI Engineering

Unlike square bracket notation, get() doesn't raise an error if the key doesn't exist.

print(student.get("city"))

Output

None

CRUD Operations

CRUD stands for:

  • Create

  • Read

  • Update

  • Delete

These are the four basic operations you'll perform on dictionaries.


Create

Adding a new key-value pair is straightforward.

student = {
    "name": "Aditya",
    "age": 22
}

student["city"] = "Varanasi"

print(student)

Output

{
 'name': 'Aditya',
 'age': 22,
 'city': 'Varanasi'
}

Read

Retrieve values using the key.

print(student["name"])

or

print(student.get("name"))

The get() method is generally preferred when the key may not exist.


Update

Updating an existing value is just as easy.

student["age"] = 23

print(student)

Output

{
 'name': 'Aditya',
 'age': 23,
 'city': 'Varanasi'
}

If the key already exists, Python simply replaces its value.


Delete

There are multiple ways to remove data.

Using del

del student["city"]

print(student)

Using pop()

age = student.pop("age")

print(age)

print(student)

Output

23

{'name': 'Aditya'}

The pop() method removes the key and also returns its value.


Common Dictionary Methods

Python provides several built-in methods that make working with dictionaries easier.


keys()

Returns all keys.

student = {
    "name": "Aditya",
    "age": 22,
    "course": "AI"
}

print(student.keys())

Output

dict_keys(['name', 'age', 'course'])

values()

Returns all values.

print(student.values())

Output

dict_values(['Aditya', 22, 'AI'])

items()

Returns both keys and values.

print(student.items())

Output

dict_items([
    ('name', 'Aditya'),
    ('age', 22),
    ('course', 'AI')
])

This method is commonly used while looping through dictionaries.

for key, value in student.items():
    print(key, ":", value)

Output

name : Aditya
age : 22
course : AI

update()

Updates one dictionary using another.

student.update({
    "city": "Varanasi",
    "age": 23
})

print(student)

Output

{
 'name': 'Aditya',
 'age': 23,
 'course': 'AI',
 'city': 'Varanasi'
}

clear()

Removes every key-value pair.

student.clear()

print(student)

Output

{}

Nested Dictionaries

Just like lists can contain other lists, dictionaries can also contain other dictionaries.

This is known as a nested dictionary.

students = {

    "student1": {
        "name": "Aditya",
        "age": 22,
        "course": "AI"
    },

    "student2": {
        "name": "Rahul",
        "age": 21,
        "course": "Web Development"
    }

}

Accessing nested values is simple.

print(students["student1"]["name"])

Output

Aditya

You can also access other nested values.

print(students["student2"]["course"])

Output

Web Development

Nested dictionaries are incredibly useful for organizing structured data.


🤖 Why Dictionaries Matter for AI

If you plan to work with AI, you'll spend a significant amount of time working with dictionaries.

For example, most APIs return JSON data, which Python represents as dictionaries.

response = {
    "model": "gpt-4",
    "tokens": 256,
    "response": "Hello, Aditya!"
}

Similarly, AI libraries often return structured information such as predictions, confidence scores, metadata, and configuration settings in dictionary format.

Whether you're using OpenAI, Gemini, Claude, LangChain, Hugging Face, or TensorFlow, dictionaries are everywhere.


JavaScript vs Python

JavaScript Python
Object Dictionary
obj.name dict["name"]
Object.keys() keys()
Object.values() values()
Object.entries() items()
delete obj.key del dict["key"]
Spread operator {...obj} update()

Common Beginner Mistakes

❌ Accessing a missing key directly

student["city"]

This raises a KeyError if "city" doesn't exist.

✅ Better approach

student.get("city")

❌ Using duplicate keys

student = {
    "name": "Aditya",
    "name": "Rahul"
}

Output

{'name': 'Rahul'}

Python keeps only the last value for duplicate keys.


Key Takeaways

✅ Dictionaries store data as key-value pairs.

✅ Keys must be unique.

✅ CRUD operations make it easy to create, read, update, and delete data.

✅ Built-in methods like keys(), values(), items(), and update() simplify dictionary operations.

✅ Nested dictionaries help organize complex and structured information.

✅ Dictionaries are one of the most commonly used data structures in AI, APIs, and JSON-based applications.


Final Thoughts

Dictionaries are the backbone of many Python applications because they provide a fast and intuitive way to organize structured data. From handling API responses and configuration files to processing AI model outputs, you'll use dictionaries in almost every real-world project.

Once you're comfortable with dictionaries, the next step is learning Functions, where you'll discover how to write reusable, modular, and maintainable Python code.


Functions in Python

As programs grow larger, repeating the same code over and over becomes difficult to maintain. Functions help us organize code into reusable blocks, making our programs cleaner, more readable, and easier to debug. Whether you're building a web application or an AI model, functions are one of the most essential concepts in Python.


What is a Function?

A function is a reusable block of code designed to perform a specific task.

Instead of writing the same code multiple times, you write it once inside a function and call it whenever needed.

Think of a function like a coffee machine.

  • You press a button (call the function).

  • The machine performs its task.

  • You get the result.

Functions help follow one of the most important programming principles:

Don't Repeat Yourself (DRY).


Defining Functions

In Python, functions are created using the def keyword.

Syntax

def function_name():
    # Function body

Example

def greet():
    print("Hello, Welcome to Python!")

Calling the function

greet()

Output

Hello, Welcome to Python!

Nothing inside a function executes until it is called.


JavaScript Comparison

JavaScript

function greet() {
    console.log("Hello, Welcome to JavaScript!");
}

greet();

Python

def greet():
    print("Hello, Welcome to Python!")

greet()

The concept is identical—the syntax is just simpler.


Parameters

Sometimes a function needs additional information to perform its task.

This information is passed using parameters.

def greet(name):
    print(f"Hello, {name}!")

Calling the function

greet("Aditya")
greet("Rahul")

Output

Hello, Aditya!
Hello, Rahul!

Here,

  • name is the parameter.

  • "Aditya" is the argument passed to the function.

A function can have multiple parameters.

def introduce(name, age):

    print(f"My name is {name} and I am {age} years old.")

Calling

introduce("Aditya", 22)

Output

My name is Aditya and I am 22 years old.

Return Values

A function doesn't always have to print something.

Often, we want it to return a value.

Python uses the return keyword.

def square(number):

    return number * number

Calling

result = square(5)

print(result)

Output

25

Once Python reaches the return statement, the function immediately stops executing.

def test():

    print("First")

    return

    print("Second")

Output

First

The second print() never runs.


Why Use return Instead of print()?

Consider these two functions.

def add(a, b):

    print(a + b)
def add(a, b):

    return a + b

The second version is much more flexible.

result = add(10, 20)

print(result * 2)

Whenever possible, return values instead of printing them.


Default Parameters

Sometimes you want a function to have a default value if no argument is provided.

def greet(name="Guest"):

    print(f"Hello, {name}")

Calling

greet()

greet("Aditya")

Output

Hello, Guest
Hello, Aditya

Default parameters make functions more flexible and reduce the number of required arguments.


Keyword Arguments

Normally, arguments are matched based on their position.

def introduce(name, age):

    print(name, age)

introduce("Aditya", 22)

Python also allows you to specify arguments by name.

introduce(age=22, name="Aditya")

Output

Aditya 22

This improves readability, especially when functions have many parameters.


*args

Sometimes you don't know how many arguments a function will receive.

Python solves this using *args.

def add(*numbers):

    print(numbers)

Calling

add(10, 20, 30)

add(1, 2, 3, 4, 5)

Output

(10, 20, 30)

(1, 2, 3, 4, 5)

Notice something interesting.

*args stores all arguments inside a tuple.

A practical example

def add(*numbers):

    return sum(numbers)

print(add(10, 20))

print(add(10, 20, 30, 40))

Output

30

100

**kwargs

While *args collects positional arguments, **kwargs collects keyword arguments.

def profile(**details):

    print(details)

Calling

profile(

    name="Aditya",

    age=22,

    role="AI Engineer"

)

Output

{
    'name': 'Aditya',
    'age': 22,
    'role': 'AI Engineer'
}

Notice that **kwargs stores everything as a dictionary.

This is one of the reasons dictionaries are so important in Python.


JavaScript Comparison

Think of **kwargs as passing an object.

JavaScript

function profile(user) {

    console.log(user);
}

profile({

    name: "Aditya",

    age: 22

});

Python

profile(

    name="Aditya",

    age=22

)

Lambda Functions

Sometimes writing an entire function is unnecessary.

For small, one-line functions, Python provides lambda functions.

Instead of

def square(x):

    return x * x

You can write

square = lambda x: x * x

Calling

print(square(5))

Output

25

Lambda functions are anonymous functions that are commonly used with functions like map(), filter(), and sorted().


🤖 Why Functions Matter for AI

Functions are one of the most important building blocks in AI applications.

You'll use them to:

  • Preprocess datasets

  • Generate prompts

  • Call AI APIs

  • Load machine learning models

  • Train models

  • Evaluate predictions

  • Clean text data

  • Build reusable AI pipelines

Instead of writing everything in one long script, functions help organize your code into small, reusable components.


JavaScript vs Python

JavaScript Python
function greet(){} def greet():
return return
Default Parameters Default Parameters
Rest Parameter ...args *args
Object Parameter **kwargs
Arrow Function Lambda Function

Common Beginner Mistakes

❌ Forgetting to return a value

def add(a, b):

    a + b

Calling

print(add(5, 3))

Output

None

✅ Correct

def add(a, b):

    return a + b

❌ Using print() instead of return

def multiply(a, b):

    print(a * b)

This makes the function harder to reuse.

Prefer

def multiply(a, b):

    return a * b

❌ Confusing *args and **kwargs

Remember:

  • *args → Multiple positional arguments → Tuple

  • **kwargs → Multiple keyword arguments → Dictionary


Key Takeaways

✅ Functions help organize code into reusable blocks.

✅ Parameters allow functions to receive input.

✅ The return keyword sends values back to the caller.

✅ Default parameters make functions more flexible.

✅ Keyword arguments improve readability.

✅ *args accepts multiple positional arguments as a tuple.

✅ **kwargs accepts multiple keyword arguments as a dictionary.

✅ Lambda functions provide a concise way to write simple, one-line functions.


Final Thoughts

Functions are one of the most valuable tools in Python because they encourage modular, reusable, and maintainable code. As your projects grow—especially in AI and machine learning—you'll quickly realize that well-designed functions make your code easier to test, debug, and extend.

Whether you're preprocessing data, building a chatbot, or training a neural network, functions will be at the core of nearly every project you write. Learning them well now will make every future Python concept much easier to understand.


Built-in Functions

One of Python's biggest strengths is its rich collection of built-in functions. These functions are available right out of the box, allowing you to perform common tasks without writing extra code. As you begin working with AI, data science, and automation, you'll find yourself using these functions almost every day.


What are Built-in Functions?

Built-in functions are predefined functions that come with Python.

Unlike user-defined functions, you don't need to import or define them before using them.

For example,

print("Hello")

len([1, 2, 3])

sum([10, 20, 30])

Python already knows how these functions work.

Let's explore some of the most useful ones.


len()

The len() function returns the number of items in an object.

It works with strings, lists, tuples, dictionaries, and sets.

text = "Artificial Intelligence"

print(len(text))

Output

23

Using a list

numbers = [10, 20, 30, 40]

print(len(numbers))

Output

4

💡 JavaScript Comparison

JavaScript uses the .length property, while Python uses the len() function.


range()

The range() function generates a sequence of numbers.

It is most commonly used inside loops.

for number in range(5):
    print(number)

Output

0
1
2
3
4

You can also specify a starting point and step size.

for number in range(2, 11, 2):
    print(number)

Output

2
4
6
8
10

Syntax

range(start, stop, step)

enumerate()

When looping through a collection, you sometimes need both the index and the value.

Instead of manually keeping track of the index, Python provides enumerate().

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output

0 Apple
1 Banana
2 Mango

This makes loops cleaner and easier to read.


zip()

The zip() function combines multiple iterables element by element.

names = ["Aditya", "Rahul", "Aman"]

scores = [95, 88, 91]

for name, score in zip(names, scores):
    print(name, score)

Output

Aditya 95
Rahul 88
Aman 91

If one iterable is shorter, zip() stops at the shortest one.


sorted()

The sorted() function returns a new sorted list without changing the original list.

numbers = [8, 2, 5, 1]

print(sorted(numbers))

Output

[1, 2, 5, 8]

Sorting in descending order

print(sorted(numbers, reverse=True))

Output

[8, 5, 2, 1]

Unlike list.sort(), the original list remains unchanged.


sum()

The sum() function returns the total of all numeric values.

numbers = [10, 20, 30, 40]

print(sum(numbers))

Output

100

min() and max()

These functions return the smallest and largest values in an iterable.

numbers = [15, 7, 29, 12]

print(min(numbers))

print(max(numbers))

Output

7
29

These functions are commonly used to find minimum and maximum values in datasets.


any()

The any() function returns True if at least one element is truthy.

values = [False, False, True]

print(any(values))

Output

True

If all values are false, it returns False.

values = [False, False, False]

print(any(values))

Output

False

all()

Unlike any(), all() returns True only if every element is truthy.

values = [True, True, True]

print(all(values))

Output

True
values = [True, False, True]

print(all(values))

Output

False

map()

The map() function applies a function to every element in an iterable.

Without map()

numbers = [1, 2, 3, 4]

result = []

for number in numbers:
    result.append(number * 2)

print(result)

Using map()

numbers = [1, 2, 3, 4]

result = list(map(lambda x: x * 2, numbers))

print(result)

Output

[2, 4, 6, 8]

map() is commonly paired with lambda functions to perform quick transformations.


filter()

The filter() function selects only the elements that satisfy a condition.

Without filter()

numbers = [1, 2, 3, 4, 5, 6]

result = []

for number in numbers:

    if number % 2 == 0:
        result.append(number)

print(result)

Using filter()

numbers = [1, 2, 3, 4, 5, 6]

result = list(filter(lambda x: x % 2 == 0, numbers))

print(result)

Output

[2, 4, 6]

filter() makes your code shorter and more expressive when selecting elements based on conditions.


🤖 Why Built-in Functions Matter for AI

These functions appear constantly in AI and data science workflows.

You'll use them to:

  • Count dataset records with len()

  • Generate sequences using range()

  • Iterate with indexes using enumerate()

  • Combine multiple datasets using zip()

  • Sort predictions with sorted()

  • Calculate totals using sum()

  • Find minimum and maximum values

  • Validate conditions with any() and all()

  • Transform data using map()

  • Filter datasets using filter()

As you move into libraries like NumPy, Pandas, PyTorch, and TensorFlow, you'll recognize many of these functions and understand how they simplify data processing.


JavaScript vs Python

JavaScript Python
.length len()
for loop range()
entries() enumerate()
Array.map() map()
Array.filter() filter()
Math.min() min()
Math.max() max()
Array.sort() sorted()

Common Beginner Mistakes

❌ Forgetting that map() returns a map object

numbers = [1, 2, 3]

result = map(lambda x: x * 2, numbers)

print(result)

Output

<map object at 0x...>

✅ Correct

result = list(map(lambda x: x * 2, numbers))

print(result)

❌ Forgetting that filter() returns a filter object

result = filter(lambda x: x > 5, numbers)

Convert it into a list when needed.

result = list(filter(lambda x: x > 5, numbers))

❌ Using sort() when you need sorted()

numbers = [3, 1, 2]

sorted_numbers = numbers.sort()

This returns None.

✅ Correct

sorted_numbers = sorted(numbers)

Key Takeaways

✅ Built-in functions save time and reduce repetitive code.

✅ len() returns the number of elements.

✅ range() generates sequences of numbers.

✅ enumerate() provides both indexes and values during iteration.

✅ zip() combines multiple iterables.

✅ sorted() returns a new sorted list.

✅ sum(), min(), and max() perform common numerical operations.

✅ any() and all() evaluate collections of boolean values.

✅ map() transforms data, while filter() selects data based on conditions.


Final Thoughts

Python's built-in functions are one of the reasons the language feels so expressive and developer-friendly. Instead of writing repetitive logic, you can rely on these functions to solve common problems with just a few lines of code.

As you continue your journey into AI engineering, you'll find yourself using many of these functions daily—whether you're preprocessing datasets, transforming model inputs, or analyzing predictions. Mastering them now will make learning advanced libraries like NumPy and Pandas much smoother.

JavaScript to Python for AI

Part 2 of 2

A step-by-step journey of learning Python from a JavaScript developer's perspective, with a focus on AI engineering. Each article covers Python fundamentals, practical examples, JavaScript comparisons, and how the concepts apply to building AI applications.

Start from the beginning

The JavaScript Developer's Guide to Learning Python - PART 1

Absolutely. I also noticed a few improvements that will make your article feel much more like it was written by an engineer rather than AI: More conversational introduction. Better spacing. "💡 Jav