Python List and Tuples Cheat Sheet

Haris Bin Nasir Avatar

·

·

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.
Copied!
['cat', 'bat', 'rat', 'elephant']

Getting Individual Values in a List with Indexes

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam[0]
Copied!
spam[1]
Copied!
spam[2]
Copied!
spam[3]

Negative Indexes

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam[-1]
Copied!
spam[-3]
Copied!
'The Array is afraid of the Array.'.format(spam[-1], spam[-3])

Getting Sublists with Slices

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam[0:4]
Copied!
spam[1:3]
Copied!
spam[0:-1]
Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam[:2]
Copied!
spam[1:]
Copied!
spam[:]

Getting a list Length with len

Copied!
spam = ['cat', 'dog', 'moose'] len(spam)

Changing Values in a List with Indexes

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aardvark' spam
Copied!
spam[2] = spam[1] spam
Copied!
spam[-1] = 12345 spam

List Concatenation and List Replication

Copied!
[1, 2, 3] + ['A', 'B', 'C']
Copied!
['X', 'Y', 'Z'] * 3
Copied!
spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] spam

Removing Values from Lists with del Statements

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] del spam[2] spam
Copied!
del spam[2] spam

Using for Loops with Lists

Copied!
supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] for i, supply in enumerate(supplies): print('Index Array in supplies is: Array'.format(str(i), supply))

Looping Through Multiple Lists with zip

Copied!
name = ['Pete', 'John', 'Elizabeth'] age = [6, 23, 44] for n, a in zip(name, age): print('Array is Array years old'.format(n, a))

The in and not in Operators

Copied!
'howdy' in ['hello', 'hi', 'howdy', 'heyas']
Copied!
spam = ['hello', 'hi', 'howdy', 'heyas'] False
Copied!
'howdy' not in spam
Copied!
'cat' not in spam

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:

Copied!
cat = ['fat', 'orange', 'loud'] size = cat[0] color = cat[1] disposition = cat[2]

You could type this line of code:

Copied!
cat = ['fat', 'orange', 'loud'] size, color, disposition = cat

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

Copied!
a, b = 'Alice', 'Bob' a, b = b, a print(a)
Copied!
print(b)

Augmented Assignment Operators

Operator Equivalent
spam += 1 spam = spam + 1
spam -= 1 spam = spam - 1
spam *= 1 spam = spam * 1
spam /= 1 spam = spam / 1
spam %= 1 spam = spam % 1

Examples:

Copied!
spam = 'Hello' spam += ' world!' spam
Copied!
bacon = ['Zophie'] bacon *= 3 bacon

Finding a Value in a List with the index Method

Copied!
spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] spam.index('Pooka')

Adding Values to Lists with append and insert

append():

Copied!
spam = ['cat', 'dog', 'bat'] spam.append('moose') spam

insert():

Copied!
spam = ['cat', 'dog', 'bat'] spam.insert(1, 'chicken') spam

Removing Values from Lists with remove

Copied!
spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('bat') spam

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

Copied!
spam = [2, 5, 3.14, 1, -7] spam.sort() spam
Copied!
spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] spam.sort() spam

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

Copied!
spam.sort(reverse=True) spam

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

Copied!
spam = ['a', 'z', 'A', 'Z'] spam.sort(key=str.lower) spam

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

Copied!
spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] sorted(spam)

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.
Copied!
eggs = ('hello', 42, 0.5) eggs[0]
Copied!
eggs[1:3]
Copied!
len(eggs)

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

Converting Types with the list and tuple Functions

Copied!
tuple(['cat', 'dog', 5])
Copied!
list(('cat', 'dog', 5))
Copied!
list('hello')

Leave a Reply

Your email address will not be published. Required fields are marked *