Python List and Tuples Cheat Sheet

Python List and Tuples Cheat Sheet

Python’s most versatile and useful data types are lists and tuples. They can be found in almost every Python program that isn’t trivial.

This cheat sheet will teach you the following: You’ll learn about the key differences between lists and tuples. You’ll discover how to define them and manipulate them. You should have a good sense of when and how to use these object types in a Python program once you’ve completed.

Python Lists Data Type

In a nutshell, a list is a collection of arbitrary items that functions similarly to an array in many other programming languages but is more versatile. In Python, lists are created by enclosing a comma-separated list of objects in square brackets ([]), as illustrated below:

The following are some of the most essential aspects of Python lists:

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.
['cat', 'bat', 'rat', 'elephant']
Code language: JSON / JSON with Comments (json)

Getting Individual Values in a List with Indexes 

spam = ['cat', 'bat', 'rat', 'elephant'] spam[0]
Code language: JavaScript (javascript)
spam[1]
Code language: CSS (css)
spam[2]
Code language: CSS (css)
spam[3]
Code language: CSS (css)

Negative Indexes

spam = ['cat', 'bat', 'rat', 'elephant'] spam[-1]
Code language: JavaScript (javascript)
spam[-3]
Code language: CSS (css)
'The {} is afraid of the {}.'.format(spam[-1], spam[-3])
Code language: JavaScript (javascript)

Getting Sublists with Slices 

spam = ['cat', 'bat', 'rat', 'elephant'] spam[0:4]
Code language: JavaScript (javascript)
spam[1:3]
Code language: CSS (css)
spam[0:-1]
Code language: CSS (css)
spam = ['cat', 'bat', 'rat', 'elephant'] spam[:2]
Code language: JavaScript (javascript)
spam[1:]
Code language: CSS (css)
spam[:]
Code language: CSS (css)

Getting a list Length with len 

spam = ['cat', 'dog', 'moose'] len(spam)
Code language: JavaScript (javascript)

Changing Values in a List with Indexes 

spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aardvark' spam
Code language: JavaScript (javascript)
spam[2] = spam[1] spam
spam[-1] = 12345 spam

List Concatenation and List Replication

[1, 2, 3] + ['A', 'B', 'C']
Code language: CSS (css)
['X', 'Y', 'Z'] * 3
Code language: CSS (css)
spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] spam
Code language: JavaScript (javascript)

Removing Values from Lists with del Statements

spam = ['cat', 'bat', 'rat', 'elephant'] del spam[2] spam
Code language: JavaScript (javascript)
del spam[2] spam
Code language: CSS (css)

Using for Loops with Lists 

supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] for i, supply in enumerate(supplies): print('Index {} in supplies is: {}'.format(str(i), supply))
Code language: PHP (php)

Looping Through Multiple Lists with zip 

name = ['Pete', 'John', 'Elizabeth'] age = [6, 23, 44] for n, a in zip(name, age): print('{} is {} years old'.format(n, a))
Code language: PHP (php)

The in and not in Operators 

'howdy' in ['hello', 'hi', 'howdy', 'heyas']
Code language: JavaScript (javascript)
spam = ['hello', 'hi', 'howdy', 'heyas'] False
Code language: PHP (php)
'howdy' not in spam
Code language: JavaScript (javascript)
'cat' not in spam
Code language: JavaScript (javascript)

The Multiple Assignment Trick 

The multiple assignment trick is a code shortcut that allows you to assign many variables to a list of values in a single line. As a result, instead of performing this:

cat = ['fat', 'orange', 'loud'] size = cat[0] color = cat[1] disposition = cat[2]
Code language: JavaScript (javascript)

You could type this line of code:

cat = ['fat', 'orange', 'loud'] size, color, disposition = cat
Code language: JavaScript (javascript)

The multiple assignment trick can also be used to swap the values in two variables:

a, b = 'Alice', 'Bob' a, b = b, a print(a)
Code language: PHP (php)
print(b)
Code language: PHP (php)

Augmented Assignment Operators 

OperatorEquivalent
spam += 1spam = spam + 1
spam -= 1spam = spam - 1
spam *= 1spam = spam * 1
spam /= 1spam = spam / 1
spam %= 1spam = spam % 1

Examples:

spam = 'Hello' spam += ' world!' spam
Code language: JavaScript (javascript)
bacon = ['Zophie'] bacon *= 3 bacon
Code language: JavaScript (javascript)

Finding a Value in a List with the index Method 

spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] spam.index('Pooka')
Code language: JavaScript (javascript)

Adding Values to Lists with append and insert 

append():

spam = ['cat', 'dog', 'bat'] spam.append('moose') spam
Code language: JavaScript (javascript)

insert():

spam = ['cat', 'dog', 'bat'] spam.insert(1, 'chicken') spam
Code language: JavaScript (javascript)

Removing Values from Lists with remove 

spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('bat') spam
Code language: JavaScript (javascript)

If a value appears in the list more than once, just the first instance will be eliminated.

Sorting the Values in a List with sort 

spam = [2, 5, 3.14, 1, -7] spam.sort() spam
spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] spam.sort() spam
Code language: JavaScript (javascript)

To have sort() sort the values in reverse order, you can provide the reverse keyword argument:

spam.sort(reverse=True) spam
Code language: PHP (php)

If you want to sort the items in alphabetical order, use the key keyword parameter str. lower in the sort() method call:

spam = ['a', 'z', 'A', 'Z'] spam.sort(key=str.lower) spam
Code language: JavaScript (javascript)

To create a new list, use the built-in function sorted:

spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] sorted(spam)
Code language: JavaScript (javascript)

Python Tuple Data Type 

A tuple is a Python type that represents an ordered collection of things.

Tuples are similar to lists in every way except for the features listed below:

  • Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
  • Tuples are immutable.
eggs = ('hello', 42, 0.5) eggs[0]
Code language: JavaScript (javascript)
eggs[1:3]
Code language: CSS (css)
len(eggs)

The fundamental difference between tuples and lists is that tuples, like strings, are immutable.

Converting Types with the list and tuple Functions 

tuple(['cat', 'dog', 5])
Code language: CSS (css)
list(('cat', 'dog', 5))
Code language: PHP (php)
list('hello')
Code language: PHP (php)
%d bloggers like this: