In Python, a list is a collection of items that are stored in a specific order. Lists can include any type of data and are very flexible to use.
# Create a list of prime numbers primes = [2, 3, 5, 7, 11] print(primes) # Output: [2, 3, 5, 7, 11] # Create an empty list empty_list = [] print(empty_list) # Output: []
You can join two lists together using the plus (+) operator. The result is a new list containing all the items from both lists in the order they appear.
# Combine two lists of items items = ['cake', 'cookie', 'bread'] total_items = items + ['biscuit', 'tart'] print(total_items) # Output: ['cake', 'cookie', 'bread', 'biscuit', 'tart']
Lists in Python can contain items of different types, such as numbers, strings, or even other lists.
# Examples of different lists numbers = [1, 2, 3, 4, 10] names = ['Jenny', 'Sam', 'Alexis'] mixed = ['Jenny', 1, 2] list_of_lists = [['a', 1], ['b', 2]] print(numbers, names, mixed, list_of_lists)
You can add items to a list using the .append() method. This method adds an item to the end of the list.
# Adding an item to the end of the list orders = ['daisies', 'periwinkle'] orders.append('tulips') print(orders) # Output: ['daisies', 'periwinkle', 'tulips']
Python lists start indexing at 0. This means the first item is at index 0, the second at index 1, and so on.
# List of names names = ['Roger', 'Rafael', 'Andy', 'Novak'] # Roger is at index 0 print(names[0]) # Output: 'Roger'
Each item in a list has an index, starting at 0. You can access any item using its index.
# Accessing items in a list berries = ['blueberry', 'cranberry', 'raspberry'] print(berries[0]) # Output: 'blueberry' print(berries[2]) # Output: 'raspberry'
Negative indices start from the end of the list. For example, -1 refers to the last item, -2 to the second last, and so on.
# List of soups soups = ['minestrone', 'lentil', 'pho', 'laksa'] print(soups[-1]) # Output: 'laksa' print(soups[-3:]) # Output: ['lentil', 'pho', 'laksa']
In a 2D list (a list of lists), you can access and modify items using two indices: one for the sublist and one for the item within the sublist.
# A 2D list of names and hobbies class_name_hobbies = [['Jenny', 'Breakdancing'], ['Alexus', 'Photography'], ['Grace', 'Soccer']] # Change Jenny's hobby to Meditation class_name_hobbies[0][1] = 'Meditation' print(class_name_hobbies) # Output: [['Jenny', 'Meditation'], ['Alexus', 'Photography'], ['Grace', 'Soccer']]
To access an item in a 2D list, use two indices: one for the sublist and one for the item in that sublist.
# 2D list of people's heights heights = [['Noelle', 61], ['Ali', 70], ['Sam', 67]] # Access Noelle's height noelles_height = heights[0][1] print(noelles_height) # Output: 61
The .remove() method removes the first occurrence of a specific item from the list.
# List of people in a line shopping_line = ['Cole', 'Kip', 'Chris', 'Sylvana', 'Chris'] # Remove the first 'Chris' shopping_line.remove('Chris') print(shopping_line) # Output: ['Cole', 'Kip', 'Sylvana', 'Chris']
The .count() method returns the number of times a specific item appears in the list.
# List of items in a backpack backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen', 'highlighter', 'pen'] # Count how many times 'pen' appears numPen = backpack.count('pen') print(numPen) # Output: 3
The len() function returns the number of items in a list.
# List of items in a knapsack knapsack = [2, 4, 3, 7, 10] # Find the number of items in the list size = len(knapsack) print(size) # Output: 5
The .sort() method arranges the items in a list in ascending order. This method changes the original list and does not return a new list.
# List of numbers exampleList = [4, 2, 1, 3] # Sort the list exampleList.sort() print(exampleList) # Output: [1, 2, 3, 4]
List slicing allows you to create a new list from a portion of an existing list. It does not change the original list.
# List of tools tools = ['pen', 'hammer', 'lever'] # Slice from index 1 to 3 tools_slice = tools[1:3] print(tools_slice) # Output: ['hammer', 'lever'] # Original list remains unchanged print(tools) # Output: ['pen', 'hammer', 'lever']
The sorted() function returns a new list that is sorted. Unlike .sort(), it does not modify the original list.
# Unsorted list of numbers unsortedList = [4, 2, 1, 3] # Get a new sorted list sortedList = sorted(unsortedList) print(sortedList) # Output: [1, 2, 3, 4]
The .insert() method adds an item at a specific position in a list. You provide the position (index) and the item to insert.
# List of people in a store line store_line = ['Karla', 'Maxium', 'Martim', 'Isabella'] # Insert 'Vikor' at position 2 store_line.insert(2, 'Vikor') print(store_line) # Output: ['Karla', 'Maxium', 'Vikor', 'Martim', 'Isabella']
The .pop() method removes the last item from the list and returns it. You can also specify an index to remove a specific item.
# List of computer science topics cs_topics = ['Python', 'Data Structures', 'Balloon Making', 'Algorithms', 'Clowns 101'] # Remove and get the last topic removed_topic = cs_topics.pop() print(cs_topics) # Output: ['Python', 'Data Structures', 'Balloon Making', 'Algorithms'] print(removed_topic) # Output: 'Clowns 101' # Remove the item at index 2 cs_topics.pop(2) print(cs_topics) # Output: ['Python', 'Data Structures', 'Algorithms']
The 'break' keyword stops the loop immediately, no matter where it is in the loop. After 'break', the program continues with the next line of code after the loop.
numbers = [0, 254, 2, -1, 3] for num in numbers: if num < 0: print("Negative number detected!") break print(num) # Output: 0 # 254 # 2 # Negative number detected!
List comprehension is a concise way to create lists in Python. The result is a new list based on an existing list or range of values.
# Create a list of squares of even numbers from 0 to 9 result = [x**2 for x in range(10) if x % 2 == 0] print(result) # Output: [0, 4, 16, 36, 64]
A 'for' loop in Python lets you repeat actions for each item in a list or range. It is useful for processing collections of items.
# Print each number in the list nums = [1, 2, 3, 4, 5] for num in nums: print(num) # Output: 1 # 2 # 3 # 4 # 5
The 'continue' keyword skips the rest of the code inside the loop for the current iteration and goes to the next iteration.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] # Print only positive numbers: for i in big_number_list: if i < 0: continue print(i) # Output: 1 # 2 # 4 # 5 # 2
The 'range()' function generates a sequence of numbers. It is commonly used with loops to repeat actions a specific number of times.
# Print numbers 0, 1, 2 for i in range(3): print(i) # Print 'WARNING' 3 times for i in range(3): print("WARNING")
An 'infinite loop' runs endlessly until it is stopped manually. Make sure to include a condition to break out of the loop when needed.
# Loop that runs only once hungry = True while hungry: print("Time to eat!") hungry = False # Loop that runs 5 times i = 1 while i < 6: print(i) i += 1
Nested loops are loops inside other loops. They are useful for processing lists of lists or performing complex iterations.
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]] # Print each name in each list for group in groups: for name in group: print(name) # Output: Jobs # Gates # Newton # Euclid # Einstein # Feynman
The 'continue' keyword in Python loops skips the current iteration and proceeds with the next one, allowing you to avoid certain cases.
# Example of using 'continue' numbers = [1, 2, -3, 4, -5] for num in numbers: if num < 0: continue print(num) # Output: 1 # 2 # 4
Functions often need some information to work with, called parameters. These are like ingredients that you give to a recipe so it can cook something specific.
def write_a_book(character, setting, special_skill): print(character + " is in " + setting + " practicing her " + special_skill) write_a_book("Alice", "Wonderland", "magic") # Output: Alice is in Wonderland practicing her magic
When defining a function, you can include several parameters to handle different pieces of information. These parameters get their values when you use the function.
def ready_for_school(backpack, pencil_case): if backpack == 'full' and pencil_case == 'full': print("I'm ready for school!") ready_for_school('full', 'full') # Output: I'm ready for school!
A function performs a specific task. For example, a function can add 1 to a number you give it and return the result.
# Define a function that adds 1 to the given number def add_one(x): return x + 1 # Use the function with different numbers print(add_one(2)) # Output: 3 print(add_one(3 + 5)) # Output: 9
Indentation is important in Python to show what code belongs to a function. Just like you need to pack both a backpack and a pencil case to be fully prepared for school, functions often need multiple lines of code indented properly.
# Define a function with indented code blocks def count_up_to(number): print("Counting up:") for x in range(number): print(x) count_up_to(3) # Output: Counting up: # 0 # 1 # 2
To use a function, just write its name followed by parentheses. This is like making a phone call to a friend to ask for help.
def do_homework(): print("Homework done!") do_homework() # Output: Homework done!
Arguments are the actual values you pass into a function’s parameters when you call it. They are like the ingredients you provide to a recipe.
def grocery_sale(store, item, price): print(store + " is selling " + item + " for " + price) grocery_sale("The Farmer’s Market", "toothpaste", "$1") # Output: The Farmer’s Market is selling toothpaste for $1
You can use keywords to specify which parameters you are providing values for, making your code clearer and more flexible.
def calculate_volume(length=1, width=1, depth=1): print("Length = " + str(length)) print("Width = " + str(width)) print("Depth = " + str(depth)) return length * width * depth calculate_volume(1, 2, 3) calculate_volume(length=5, depth=2, width=4) # Output: Length = 5 # Width = 4 # Depth = 2
Functions can return more than one value at a time. This is useful when you need to give back multiple results from a function.
def square_values(x, y, z): x_squared = x * x y_squared = y * y z_squared = z * z return x_squared, y_squared, z_squared squares = square_values(3, 4, 5) print(squares) # Output: (9, 16, 25)
Variables inside functions are different from those outside. Inside the function, they are local and only available there.
a = 5 # Define a function that uses a local variable def local_example(): a = 2 print(a) local_example() # Output: 2 print(a) # Output: 5
A function can send back a result using the `return` keyword. This is like giving back a result after performing some calculations.
def check_leap_year(year): if year % 4 == 0: return str(year) + " is a leap year." else: return str(year) + " is not a leap year." year = 2024 print(check_leap_year(year)) # Output: 2024 is a leap year.
Global variables are available everywhere in your code, not just inside functions. Functions can use these global variables as well.
a = "Hello" # Define a function that uses a global variable def print_greeting(): print(a) print_greeting() # Output: Hello
Variables defined inside a function only exist within that function. They can't be used outside of it.
def my_function(value): print(value) my_function(7) # Output: 7 # Trying to print `value` outside the function will cause an error # print(value) # This line will cause an error
The command 'pwd' shows the full path of the current directory you are in. It helps you see where you are in the file system.
$ pwd /Users/sonny/Downloads
The command 'mkdir' creates a new folder. You can specify the location where you want to create this folder, or it will create it in the current directory.
$ mkdir new-folder $ ls old-folder new-folder
The command 'ls' lists all the files and folders in the directory you're currently in. You can also specify a different directory to see its contents.
$ ls Desktop resume.pdf photo.png
The command 'cd' is used to move between directories. You can go into a specific directory or move up one level.
$ cd some-folder $ cd ..
A computer’s file system arranges files and folders so you can easily find and access them. Think of it as a structured way to keep everything in place.
$ touch grocery-list.txt
The command 'touch' creates a new, empty file with the name you provide in the current directory.
$ touch newfile.txt $ ls newfile.txt
The command line is a tool where you type commands to perform tasks like navigating directories or running programs. The shell prompt is often shown as '$'.
The command line allows you to run various commands to manage files and run programs. The default shell in Unix systems is called Bash.
The .format() method lets you insert values into a string where you have placeholders marked by {}. You can replace these placeholders with specific values.
msg1 = 'Fred scored {} out of {} points.' print(msg1.format(3, 10)) # Prints: Fred scored 3 out of 10 points. msg2 = 'Fred {verb} a {adjective} {noun}.' print(msg2.format(adjective='fluffy', verb='tickled', noun='hamster')) # Prints: Fred tickled a fluffy hamster.
The .lower() method converts all uppercase letters in a string to lowercase.
greeting = "Welcome To Chili's" print(greeting.lower()) # Prints: welcome to chili's
The .strip() method removes any leading and trailing spaces or specific characters from a string.
text1 = ' apples and oranges ' print(text1.strip()) # Prints: apples and oranges text2 = '...+...lemons and limes...-...' print(text2.strip('.')) # Prints: +...lemons and limes...- print(text2.strip('.+')) # Prints: lemons and limes...- print(text2.strip('.+-')) # Prints: lemons and limes
The .title() method capitalizes the first letter of each word in a string and makes all other letters lowercase.
my_var = "dark knight" print(my_var.title()) # Prints: Dark Knight
The .split() method breaks a string into a list of smaller strings based on a specified separator.
text = "Silicon Valley" print(text.split()) # Prints: ['Silicon', 'Valley'] print(text.split('i')) # Prints: ['S', 'l', 'con Valley']
The .find() method searches for a substring within a string and returns its position. If the substring isn’t found, it returns -1.
mountain_name = "Mount Kilimanjaro" print(mountain_name.find("o")) # Prints: 1
The .replace() method replaces occurrences of a specified substring with another substring.
fruit = "Strawberry" print(fruit.replace('r', 'R')) # Prints: StRawbeRRy
The .upper() method converts all lowercase letters in a string to uppercase.
dinosaur = "T-Rex" print(dinosaur.upper()) # Prints: T-REX
The .join() method combines a list of strings into a single string with a specified separator.
x = "-".join(["Codecademy", "is", "awesome"]) print(x) # Prints: Codecademy-is-awesome
To include special characters like quotes in a string, use backslashes to escape them.
txt = "She said \"Never let go\"." print(txt) # Prints: She said "Never let go".
The 'in' syntax checks if a specific character or substring exists in a string. It returns True if found, otherwise False.
game = "Popular Nintendo Game: Mario Kart" print("l" in game) # Prints: True print("x" in game) # Prints: False
You can access individual characters or substrings in a string using indexing and slicing. Indexing retrieves a single character, while slicing gets a substring.
str = 'yellow' print(str[1]) # Prints: e print(str[-1]) # Prints: w print(str[4:6]) # Prints: ow print(str[:4]) # Prints: yell print(str[-3:]) # Prints: low
You can loop through each character in a string using a for loop to process or print each one.
str = "hello" for c in str: print(c) # Prints each character: # h e l l o
Use the len() function to find out how many characters are in a string or items in a list.
length = len("Hello") print(length) # Prints: 5 colors = ['red', 'yellow', 'green'] print(len(colors)) # Prints: 3
To combine strings together, use the '+' operator to join them into one continuous string.
x = 'One fish, ' y = 'two fish.' z = x + y print(z) # Prints: One fish, two fish.
Strings in Python are immutable, which means they cannot be changed after they are created. To modify a string, you create a new one instead.
str = 'hello' str = str + ' world' print(str) # Prints: hello world
Trying to access an index that is out of range in a string will result in an IndexError. Make sure your index is within the valid range.
str = 'hello' print(str[10]) # This will raise an IndexError
Python has a module called datetime for handling dates and times. You can create and work with dates and times using this module.
import datetime # Create a date object for February 16, 2019 feb_16_2019 = datetime.date(2019, 2, 16) print(feb_16_2019) # Prints: 2019-02-16 # Create a time object for 13:48:05 time_13_48min_5sec = datetime.time(13, 48, 5) print(time_13_48min_5sec) # Prints: 13:48:05 # Create a datetime object for February 16, 2019, at 13:48:05 timestamp = datetime.datetime(2019, 2, 16, 13, 48, 5) print(timestamp) # Prints: 2019-02-16 13:48:05
The 'as' keyword allows you to create a shortcut name (alias) for a module, which can make your code shorter and easier to read.
# Importing matplotlib.pyplot as plt from matplotlib import pyplot as plt plt.plot(x, y) # Importing calendar as c import calendar as c print(c.month_name[1]) # Prints: January
You can import modules in different ways. You can use 'import module', 'from module import function', or 'from module import *'. Using 'from module import *' is not recommended as it may clutter your code.
# Three ways to import modules: # 1. Import the whole module import module module.function() # 2. Import specific functions from a module from module import function function() # 3. Import everything from a module (not recommended) from module import * function()
The random module provides functions to generate random numbers and select random items from a list.
import random # Get a random integer between 0 and 10 r1 = random.randint(0, 10) print(r1) # Prints a random integer between 0 and 10 # Pick a random item from a list seq = ["a", "b", "c", "d", "e"] r2 = random.choice(seq) print(r2) # Prints a random element from the list
Modules can be imported in different ways. Importing everything from a module with 'from module import *' is discouraged because it can make your code harder to understand.
# file1.py # def greet(): # return "Hello World" # file2.py import file1 # Now we can use the greet function from file1 print(file1.greet()) # Prints: Hello World
In a Python dictionary, you can get a value by using its key inside square brackets. You can also change a value by using its key and assigning a new value. If the key doesn’t exist, you’ll get an error called KeyError.
my_dict = {"song": "Estranged", "artist": "Guns N' Roses"} print(my_dict["song"]) my_dict["song"] = "Paradise City" print(my_dict["song"]) # Output: Paradise City
A dictionary in Python is defined using curly braces ({}) with key-value pairs separated by colons (:). Each key-value pair is separated by a comma (,).
my_dict = {"q1": "Ashley", "q2": "Dolly"} print(my_dict) # Output: {'q1': 'Ashley', 'q2': 'Dolly'}
You can combine two dictionaries using the .update() method. This method will add key-value pairs from one dictionary to another, updating values for existing keys.
dict1 = {'color': 'blue', 'shape': 'circle'} dict2 = {'color': 'red', 'number': 42} dict1.update(dict2) print(dict1) # Output: {'color': 'red', 'shape': 'circle', 'number': 42}
Dictionaries can store different types of values, including strings, numbers, lists, and even other dictionaries. However, keys must be immutable types like strings, numbers, or tuples.
my_dict = { 1: 'hello', 'two': True, '3': [1, 2, 3], 'Four': {'fun': 'addition'}, 5.0: 5.5 } print(my_dict) # Output: {1: 'hello', 'two': True, '3': [1, 2, 3], 'Four': {'fun': 'addition'}, 5.0: 5.5}
You can use methods like .keys(), .values(), and .items() to get information about the keys, values, and key-value pairs in a dictionary.
my_dict = {"a": "apple", "b": "banana", "c": "cherry"} print(my_dict.keys()) # dict_keys(['a', 'b', 'c']) print(my_dict.values()) # dict_values(['apple', 'banana', 'cherry']) print(my_dict.items()) # dict_items([('a', 'apple'), ('b', 'banana'), ('c', 'cherry')])
The get() method allows you to safely retrieve a value from a dictionary. If the key doesn’t exist, you can provide a default value to return instead of causing an error.
my_dict = {"name": "Victor"} print(my_dict.get("name")) # Output: Victor print(my_dict.get("nickname")) # Output: None print(my_dict.get("nickname", "No nickname found")) # Output: No nickname found
You can remove an item from a dictionary using the .pop() method by specifying the key of the item you want to remove. The method returns the value of the removed item.
museums = {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre', 'Athens': 'The Acropolis Museum'} museums.pop('Athens') print(museums) # Output: {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre'}
The __repr__() method in Python defines how an object should be represented as a string. This method only takes one parameter, self, and it should return a string that describes the object.
class Employee: def __init__(self, name): self.name = name def __repr__(self): return self.name john = Employee('John') print(john) # Output: John
In Python, methods are functions that belong to a class. The first argument of a method is always the object that calls it, usually named self.
class Dog: def bark(self): print("Woof") my_dog = Dog() my_dog.bark() # Output: Woof
To use a class in Python, you need to create an instance of it. This is done by calling the class as if it were a function.
class Car: "This is an empty class" pass my_car = Car()
Class variables are shared among all instances of a class. They are defined inside the class but outside of any methods.
class MyClass: class_variable = "I am a Class Variable!" obj1 = MyClass() obj2 = MyClass() print(obj1.class_variable) # Output: I am a Class Variable! print(obj2.class_variable) # Output: I am a Class Variable!
The __init__() method initializes a new object of a class. It sets up the initial state of the object when it is created.
class Animal: def __init__(self, voice): self.voice = voice cat = Animal('Meow') print(cat.voice) # Output: Meow dog = Animal('Woof') print(dog.voice) # Output: Woof
The type() function returns the type of an object, which helps you understand what kind of data you are working with.
num = 1 print(type(num)) # Output:num = 1.1 print(type(num)) # Output: num = 'text' print(type(num)) # Output: num = None print(type(num)) # Output:
In Python, a class is like a blueprint for creating objects. The __init__() method is called when a new object is created from the class.
class Animal: def __init__(self, name, legs): self.name = name self.legs = legs # Create instances of the Animal class cat = Animal('Cat', 4) dog = Animal('Dog', 4)
The dir() function shows the list of attributes and methods available for an object or class. This helps you see what you can do with it.
class Employee: def __init__(self, name): self.name = name def print_name(self): print("Hi, I'm " + self.name) print(dir()) # Lists all attributes in the current scope print(dir(Employee)) # Lists attributes and methods of the Employee class
The __main__ keyword is used to check if a Python file is being run as the main program or if it's being imported into another file.
# If this script is run directly, __main__ will be its name. print(__name__) # Output: __main__
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!