Skip to content

Chapter 5 of 7

Data Structures

Lists are mutable, ordered sequences defined with square brackets, such as mylist = [1, 2, 3]. You access elements by index using mylist[0] for the first element, and negative indices count from the end. Common list methods include append(x) to add an item at the end, pop() to remove and return the last item, insert(i, x) to insert at a specific position, remove(x) to remove the first occurrence of a value, sort() to sort in place, and reverse() to reverse the order.

Tuples are immutable sequences created with parentheses or simply by separating values with commas, like t = (1, 2, 3). Because they cannot be changed after creation, tuples are useful for representing fixed collections of related data, such as coordinates or RGB color values. Dictionaries map keys to values using the syntax d = {'key': 'value'}. Keys must be immutable types, and you access values with d['key']. Sets are unordered collections of unique elements defined with curly braces, like s = {1, 2}, and they support operations such as add(), remove(), union, and intersection.

Strings are immutable sequences of characters, and you can extract substrings using slicing. The expression s[1:3] returns a substring from index 1 up to but not including index 3, and you can provide a step with s[::2] to skip every other character. Common string methods include upper(), lower(), strip() for removing whitespace, split() for breaking into a list, join() for combining an iterable into a string, find() for locating a substring, and replace() for substituting characters. F-strings, introduced in Python 3.6, offer a concise way to interpolate values into strings: f'Hello {name}' substitutes the value of the variable name directly into the string.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.