Beginners Python Cheat Sheet PCC Lists
Beginners Python Cheat Sheet PCC Lists
You can add elements to the end of a list, or you can insert
them wherever you like in a list.
Sorting a list
The sort() method changes the order of a list
permanently. The sorted() function returns a copy of the
list, leaving the original list unchanged. You can sort the
Adding an element to the end of the list items in a list in alphabetical order, or reverse alphabetical
users.append('amy') order. You can also reverse the original order of the list.
Keep in mind that lowercase and uppercase letters may
Starting with an empty list affect the sort order.
What are lists?
users = [] Sorting a list permanently
A list stores a series of items in a particular order. users.append('val')
Lists allow you to store sets of information in one users.append('bob') users.sort()
place, whether you have just a few items or millions users.append('mia')
Sorting a list permanently in reverse alphabetical
of items. Lists are one of Python's most powerful order
Inserting elements at a particular position
features readily accessible to new programmers, and
they tie together many important concepts in users.insert(0, 'joe') users.sort(reverse=True)
programming. users.insert(3, 'bea')
Sorting a list temporarily
Removing elements print(sorted(users))
Defining a list You can remove elements by their position in a list, or by print(sorted(users, reverse=True))
Use square brackets to define a list, and use commas to the value of the item. If you remove an item by its value,
separate individual items in the list. Use plural names for Reversing the order of a list
Python removes only the first item that has that value.
lists, to make your code easier to read. users.reverse()
Deleting an element by its position
Making a list
del users[-1]
users = ['val', 'bob', 'mia', 'ron', 'ned'] Looping through a list
Removing an item by its value Lists can contain millions of items, so Python provides an
efficient way to loop through all the items in a list. When
users.remove('mia') you set up a loop, Python pulls each item from the list one
Accessing elements
Individual elements in a list are accessed according to their at a time and stores it in a temporary variable, which you
position, called the index. The index of the first element is Popping elements provide a name for. This name should be the singular
0, the index of the second element is 1, and so forth. If you want to work with an element that you're removing version of the list name.
Negative indices refer to items at the end of the list. To get from the list, you can "pop" the element. If you think of the The indented block of code makes up the body of the
a particular element, write the name of the list and then list as a stack of items, pop() takes an item off the top of loop, where you can work with each individual item. Any
the index of the element in square brackets. the stack. By default pop() returns the last element in the lines that are not indented run after the loop is completed.
list, but you can also pop elements from any position in the Printing all items in a list
Getting the first element list.
first_user = users[0] for user in users:
Pop the last item from a list
print(user)
Getting the second element most_recent_user = users.pop()
print(most_recent_user) Printing a message for each item, and a separate
second_user = users[1] message afterwards
Pop the first item in a list
Getting the last element for user in users:
first_user = users.pop(0) print(f"Welcome, {user}!")
newest_user = users[-1] print(first_user)
Modifying individual items print("Welcome, we're glad to see you all!")
Once you've defined a list, you can change individual List length
elements in the list. You do this by referring to the index of the The len() function returns the number of items in a list.
item you want to modify.
Find the length of a list
Changing an element num_users = len(users)
users[0] = 'valerie' users[-2] = 'ronald' print(f"We have {num_users} users.")
Copying a list
The range() function To copy a list make a slice that starts at the first item and
You can use the range() function to work with a set of ends at the last item. If you try to copy a list without using this approach, whatever you do to the copied list will affect the original list
numbers efficiently. The range() function starts at 0 by Making a copy of a list
default, and stops one number below the number passed to finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] copy_of_finishers = finishers[:]
it. You can use the list() function to efficiently generate a
large list of numbers.
Printing the numbers 0 to 1000
for number in range(1001):
print(number)
List comprehensions
Printing the numbers 1 to 1000 You can use a loop to generate a list based on a range of
for number in range(1, 1001): numbers or on another list. This is a common operation, so Python offers a more efficient way to do it. List comprehensions may loo
print(number) To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input v
Using a loop to generate a list of square numbers
Making a list of numbers from 1 to a million squares = []
for x in range(1, 11): square = x**2 squares.append(square)
numbers = list(range(1, 1000001))
Using a comprehension to generate a list of square numbers
squares = [x**2 for x in range(1, 11)]
Simple statistics Using a loop to convert a list of names to upper case
There are a number of simple statistical operations you can names = ['kai', 'abe', 'ada', 'gus', 'zoe']
run on a list containing numerical data.
Finding the minimum value in a list upper_names = [] for name in names:
upper_names.append(name.upper())
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
youngest = min(ages)
Using a comprehension to convert a list of names to upper case
names = ['kai', 'abe', 'ada', 'gus', 'zoe']
Finding the maximum value
upper_names = [name.upper() for name in names]
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
oldest = max(ages)
Finding the sum of all values
ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77]
total_years = sum(ages)
Slicing a list
You can work with any set of elements from a list. A portion
of a list is called a slice. To slice a list start with the index of
the first item you want, then add a colon and the index after
the last item you want. Leave off the first index to start at
the beginning of the list, and leave off the last index to slice
through the end of the list.
Getting the first three items
finishers = ['kai', 'abe', 'ada', 'gus', 'zoe'] Styling your code
first_three = finishers[:3] Readability counts
Use four spaces per indentation level.
Getting the middle three items
Keep your lines to 79 characters or fewer.
middle_three = finishers[1:4] Use single blank lines to group parts of your program visually.
Getting the last three items
last_three = finishers[-3:]