This document explains Python lists and tuples, including indexing, slicing mutability, concatenation, nesting, methods, and aliasing, with practical examples for data manipulation.
This document covers Python lists and tuples, including indexing, slicing, mutability, concatenation, nesting, methods, and aliasing, with practical examples for data manipulation and structure.
Lists and tuples are compound data types and key data structures in Python. Both are ordered sequences, but differ in mutability and usage.
Tuples are ordered sequences, expressed as comma-separated elements within parentheses. They can contain different types (strings, integers, floats), but the variable type is always tuple.
ratings[0], ratings[1], ratings[-1]ratings[:3] for first three elements, ratings[-2:] for last two elements.len(ratings)Tuples are immutable; their values cannot be changed. Assigning a tuple to another variable creates a reference to the same object.
sorted(ratings) returns a new sorted list.Lists are ordered sequences represented with square brackets. Lists are mutable and can contain strings, floats, integers, and other lists or tuples.
L[0], L[1], L[-1]L[-2:] for last two elements.len(L)L + L2L.extend([new1, new2])L.append("A")L[0] = "HardRock"del L[0]"A B C".split() or "A,B,C".split(",")Lists are mutable; changes affect all references unless cloned.
b = a (both reference same list)a changes b.b = a[:] (creates a new copy)Both lists and tuples can be nested. Standard indexing applies for accessing nested elements.
Python lists and tuples provide flexible ways to store and manipulate ordered data. Understanding mutability, indexing, slicing, and methods is essential for effective data management.
(3) Tuples are immutable and cannot be changed after creation.
| Concept | Description |
|---|---|
| A. Aliasing | 1. Creating a new copy of a list |
| B. Cloning | 2. Multiple names referencing the same object |
| C. Extend | 3. Adding multiple elements to a list |
| D. Append | 4. Adding a single element to a list |
A-2, B-1, C-3, D-4.
Lists in Python can be changed after creation, while tuples cannot.
True. Lists are mutable, tuples are immutable.