In Python, lists are ordered collections of items that allow for easy use of a set of data.
primes = [2, 3, 5, 7, 11] print(primes) empty_list = []
List values are placed in between square brackets [ ], separated by commas. The values in a list do not need to be unique (the same value can be repeated).
items = ['cake', 'cookie', 'bread'] total_items = items + ['biscuit', 'tart'] print(total_items) # Result: ['cake', 'cookie', 'bread', 'biscuit', 'tart']
Lists can contain different data types, including numbers, strings, and even other lists.
numbers = [1, 2, 3, 4, 10] names = ['Jenny', 'Sam', 'Alexis'] mixed = ['Jenny', 1, 2] list_of_lists = [['a', 1], ['b', 2]]
Use the .append() method to add an item to the end of a list.
orders = ['daisies', 'periwinkle'] orders.append('tulips') print(orders) # Result: ['daisies', 'periwinkle', 'tulips']
List indexing in Python starts at 0. For adding one item at a time, use the .append() method.
names = ['Roger', 'Rafael', 'Andy', 'Novak']
Access list elements by their index, starting from 0.
berries = ["blueberry", "cranberry", "raspberry"] berries[0] # "blueberry" berries[2] # "raspberry"
Negative indices access elements from the end of the list.
soups = ['minestrone', 'lentil', 'pho', 'laksa'] soups[-1] # 'laksa' soups[-3:] # 'lentil', 'pho', 'laksa' soups[:-2] # 'minestrone', 'lentil'
Modify elements in a 2D list by specifying the indices for sublists and their elements.
# A 2D list of names and hobbies class_name_hobbies = [["Jenny", "Breakdancing"], ["Alexus", "Photography"], ["Grace", "Soccer"]] class_name_hobbies[0][1] = "Meditation" print(class_name_hobbies) # Output: [["Jenny", "Meditation"], ["Alexus", "Photography"], ["Grace", "Soccer"]]
Access elements in a 2D list using two indices: one for the sublist and one for the element within that sublist.
# 2D list of people's heights heights = [["Noelle", 61], ["Ali", 70], ["Sam", 67]] noelles_height = heights[0][1] print(noelles_height) # Output: 61
Remove the first occurrence of a value from a list using the .remove() method.
# Create a list shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"] # Removes the first occurrence of "Chris" shopping_line.remove("Chris") print(shopping_line) # Output: ["Cole", "Kip", "Sylvana", "Chris"]
Tuples are immutable sequences of elements. They cannot be modified after creation.
my_tuple = ('abc', 123, 'def', 456, 789, 'ghi') len(my_tuple) # returns length of tuple max(my_tuple) # returns maximum value of tuple min(my_tuple) # returns minimum value of tuple my_tuple.index(123) # returns the position of the value 123 my_tuple.count('abc') # returns the number of occurrences of 'abc'
Count the occurrences of a specific value in a list using the .count() method.
backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen', 'highlighter', 'pen'] numPen = backpack.count('pen') print(numPen) # Output: 3
Find the number of items in a list using the len() function.
knapsack = [2, 4, 3, 7, 10] size = len(knapsack) print(size) # Output: 5
Sort a list in ascending order using the .sort() method.
exampleList = [4, 2, 1, 3] exampleList.sort() print(exampleList) # Output: [1, 2, 3, 4]
Slice a list to access a subset of its elements.
tools = ['pen', 'hammer', 'lever'] tools_slice = tools[1:3] # ['hammer', 'lever'] tools_slice[0] = 'nail' # Original list is unaltered: print(tools) # ['pen', 'hammer', 'lever']
Sort a list and return a new sorted list using the sorted() function.
unsortedList = [4, 2, 1, 3] sortedList = sorted(unsortedList) print(sortedList) # Output: [1, 2, 3, 4]
Insert an element at a specific position in a list using the .insert() method.
# Here is a list representing a line of people at a store store_line = ["Karla", "Maxium", "Martim", "Isabella"] # Insert "Vikor" after "Maxium" and before "Martim" store_line.insert(2, "Vikor") print(store_line) # Output: ['Karla', 'Maxium', 'Vikor', 'Martim', 'Isabella']
Remove and return an element from a list using the .pop() method.
# Pop the last element cs_topics = ["Python", "Data Structures", "Balloon Making", "Algorithms", "Clowns 101"] removed_element = cs_topics.pop() print(cs_topics) print(removed_element) # Output: ['Python', 'Data Structures', 'Balloon Making', 'Algorithms'] # 'Clowns 101'
The break keyword exits a loop immediately, regardless of the iteration number.
numbers = [0, 254, 2, -1, 3] for num in numbers: if (num < 0): print("Negative number detected!") break print(num) # 0 # 254 # 2 # Negative number detected!
Create a list based on existing lists using a concise syntax.
# List comprehension for the squares of all even numbers between 1 and 10 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_squares = [x**2 for x in numbers if x % 2 == 0] print(even_squares) # Output: [4, 16, 36, 64, 100]
Generate a sequence of numbers using the range() function, often used in loops.
for i in range(5): print(i) # Output: 0, 1, 2, 3, 4
Use a for loop to iterate over a sequence or a collection of items.
animals = ['cat', 'dog', 'rabbit'] for animal in animals: print(animal) # Output: cat, dog, rabbit
Use a while loop to execute code as long as a condition is true.
i = 0 while i < 5: print(i) i += 1 # Output: 0, 1, 2, 3, 4
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!