0% found this document useful (0 votes)
179 views

Learn Python 3 - Lists Cheatsheet - Codecademy

Lists are ordered collections of items that allow for easy use of a set of data in Python. Lists values are placed in square brackets and separated by commas. Empty lists do not contain any values. Lists can be added together using + and contain multiple data types. Common list methods include append() to add items, count() to count occurrences of an item, and len() to determine length. List indices begin at 0 and can be positive or negative. Slices of a list can be selected using start:end indices.

Uploaded by

SAURABH SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views

Learn Python 3 - Lists Cheatsheet - Codecademy

Lists are ordered collections of items that allow for easy use of a set of data in Python. Lists values are placed in square brackets and separated by commas. Empty lists do not contain any values. Lists can be added together using + and contain multiple data types. Common list methods include append() to add items, count() to count occurrences of an item, and len() to determine length. List indices begin at 0 and can be positive or negative. Slices of a list can be selected using start:end indices.

Uploaded by

SAURABH SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Cheatsheets / Learn Python 3

Lists
Lists
In Python, lists are ordered collections of items that
allow for easy use of a set of data. primes = [2, 3, 5, 7, 11]
List values are placed in between square brackets [ print(primes)
] , separated by commas. It is good practice to put a
space between the comma and the next value. The empty_list = []
values in a list do not need to be unique (the same value
can be repeated).
Empty lists do not contain any values within the square
brackets.

Adding Lists Together


In Python, lists can be added to each other using the
plus symbol + . As shown in the code block, this will items = ['cake', 'cookie', 'bread']
result in a new list containing the same items in the total_items = items + ['biscuit', 'tart']
same order with the first list’s items coming first. print(total_items)
Note: This will not work for adding one item at a time # Result: ['cake', 'cookie', 'bread',
(use .append() method). In order to add one item, 'biscuit', 'tart']
create a new list with a single value and then use the
plus symbol to add the list.

Python Lists: Data Types


In Python, lists are a versatile data type that can contain
multiple different data types within the same square numbers = [1, 2, 3, 4, 10]
brackets. The possible data types within a list include names = ['Jenny', 'Sam', 'Alexis']
numbers, strings, other objects, and even other lists. mixed = ['Jenny', 1, 2]
list_of_lists = [['a', 1], ['b', 2]]

List Method .append()


In Python, you can add values to the end of a list using
the .append() method. This will place the object orders = ['daisies', 'periwinkle']
passed in as a new element at the very end of the list. orders.append('tulips')
Printing the list afterwards will visually show the print(orders)
appended value. This .append() method is not to # Result: ['daisies', 'periwinkle',
be confused with returning an entirely new list with the 'tulips']
passed object.

/
Aggregating Iterables Using zip()
In Python, data types that can be iterated (called
iterables) can be used with the zip() function to owners_names = ['Jenny', 'Sam', 'Alexis']
aggregate data. The zip() function takes iterables, dogs_names = ['Elphonse', 'Dr. Doggy DDS',
aggregates corresponding elements based on the 'Carter']
iterables passed in, and returns an iterator. Each element owners_dogs = zip(owners_names,
of the returned iterator is a tuple of values. dogs_names)
As shown in the example, zip() is aggregating the print(list(owners_dogs))
data between the owners’ names and the dogs’ names # Result: [('Jenny', 'Elphonse'), ('Sam',
to match the owner to their dogs. zip() returns an 'Dr.Doggy DDS'), ('Alexis', 'Carter')]
iterator containing the data based on what the user
passes to the function. Empty iterables passed in will
result in an empty iterator. To view the contents of the
iterator returned from zip() , we can cast it as a list
by using the list() function and printing the results.

List Item Ranges Including First or Last Item


In Python, when selecting a range of list items, if the first
item to be selected is at index 0 , no index needs to be items = [1, 2, 3, 4, 5, 6]
specified before the : . Similarly, if the last item
selected is the last item in the list, no index needs to be # All items from index `0` to `3`
specified after the : . print(items[:4])

# All items from index `2` to the last


item, inclusive
print(items[2:])

List Method .count()


The .count() Python list method searches a list for
whatever search term it receives as an argument, then backpack = ['pencil', 'pen', 'notebook',
returns the number of matching entries found. 'textbook', 'pen', 'highlighter', 'pen']
numPen = backpack.count('pen')
print(numPen)
# Output: 3

Determining List Length with len()


The Python len() function can be used to determine
the number of items found in the list it accepts as an knapsack = [2, 4, 3, 7, 10]
argument. size = len(knapsack)
print(size)
# Output: 5

/
Zero-Indexing
In Python, list index begins at zero and ends at the
length of the list minus one. For example, in this list, names = ['Roger', 'Rafael', 'Andy',
'Andy' is found at index 2 . 'Novak']

List Method .sort()


The .sort() Python list method will sort the
contents of whatever list it is called on. Numerical lists exampleList = [4, 2, 1, 3]
will be sorted in ascending order, and lists of Strings will exampleList.sort()
be sorted into alphabetical order. It modifies the original print(exampleList)
list, and has no return value. # Output: [1, 2, 3, 4]

List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices start at berries = ["blueberry", "cranberry",
0 and increment by one. "raspberry"]
To access a list element by index, square bracket
notation is used: list[index] . berries[0] # "blueberry"
berries[2] # "raspberry"

Negative List Indices


Negative indices for lists in Python can be used to
reference elements in relation to the end of a list. This soups = ['minestrone', 'lentil', 'pho',
can be used to access single list elements or as part of 'laksa']
defining a list range. For instance: soups[-1] # 'laksa'
soups[-3:] # 'lentil', 'pho', 'laksa'

To select the last element, my_list[-1] .
soups[:-2] # 'minestrone', 'lentil'
● To select the last three elements,
my_list[-3:] .
● To select everything except the last two elements,
my_list[:-2] .

List Slicing
A slice, or sub-list of Python list elements can be
selected from a list using a colon-separated starting and tools = ['pen', 'hammer', 'lever']
ending point. tools_slice = tools[1:3] # ['hammer',
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . The tools_slice[0] = 'nail'
slice will include the START_NUMBER index, and
everything until but excluding the END_NUMBER item. # Original list is unaltered:
When slicing a list, a new list is returned, so if the slice is print(tools) # ['pen', 'hammer', 'lever']
saved and then altered, the original list remains the
same.

/
sorted() Function
The Python sorted() function accepts a list as an
argument, and will return a new, sorted list containing unsortedList = [4, 2, 1, 3]
the same elements as the original. Numerical lists will be sortedList = sorted(unsortedList)
sorted in ascending order, and lists of Strings will be print(sortedList)
sorted into alphabetical order. It does not modify the # Output: [1, 2, 3, 4]
original, unsorted list.

You might also like