Python 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, we create lists 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.
- Indexing is used to access list elements.
- We can nest lists to arbitrary depths.
- Lists are mutable.
- Lists are dynamic.
['cat', 'bat', 'rat', 'elephant']
Getting Individual Values in a List with Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0]
spam[1]
spam[2]
spam[3]
Negative Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[-1]
spam[-3]
'The {} is afraid of the {}.'.format(spam[-1], spam[-3])
Getting Sublists with Slices
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4]
spam[1:3]
spam[0:-1]
spam = ['cat', 'bat', 'rat', 'elephant']
spam[:2]
spam[1:]
spam[:]
Getting a list Length with len
spam = ['cat', 'dog', 'moose']
len(spam)
Changing Values in a List with Indexes
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1] = 'aardvark'
spam
spam[2] = spam[1]
spam
spam[-1] = 12345
spam
List Concatenation and List Replication
[1, 2, 3] + ['A', 'B', 'C']
['X', 'Y', 'Z'] * 3
spam = [1, 2, 3]
spam = spam + ['A', 'B', 'C']
spam
Removing Values from Lists with del Statements
spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
spam
del spam[2]
spam
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))
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))
The in and not in Operators
'howdy' in ['hello', 'hi', 'howdy', 'heyas']
spam = ['hello', 'hi', 'howdy', 'heyas']
False
'howdy' not in spam
'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:
cat = ['fat', 'orange', 'loud']
size = cat[0]
color = cat[1]
disposition = cat[2]
You could type this line of code:
cat = ['fat', 'orange', 'loud']
size, color, disposition = cat
We use the multiple assignment trick to swap the values in two variables:
a, b = 'Alice', 'Bob'
a, b = b, a
print(a)
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:
spam = 'Hello'
spam += ' world!'
spam
bacon = ['Zophie']
bacon *= 3
bacon
Finding a Value in a List with the index Method
spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
spam.index('Pooka')
Adding Values to Lists with append and insert
append():
spam = ['cat', 'dog', 'bat']
spam.append('moose')
spam
insert():
spam = ['cat', 'dog', 'bat']
spam.insert(1, 'chicken')
spam
Removing Values from Lists with remove
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
spam = [2, 5, 3.14, 1, -7]
spam.sort()
spam
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:
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:
spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
spam
To create a new list, use the built-in function sorted:
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.
eggs = ('hello', 42, 0.5)
eggs[0]
eggs[1:3]
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])
list(('cat', 'dog', 5))
list('hello')
Conclusion
Understanding the differences between Python lists and tuples is crucial for effective data handling in your programs. Lists offer flexibility with mutable data and various manipulation methods, while tuples provide a fixed, immutable structure for storing ordered collections. By mastering these data types and their associated operations, you can enhance your Python programming skills and write more efficient, reliable code.
Happy Coding…!!!
Leave a Reply