Lists and Tuples
Listโ
A list is an ordered, mutable collection.
Creating Listsโ
# Empty list
empty = []
empty = list()
# List with values
numbers = [1, 2, 3, 4, 5]
names = ["ํ๊ธธ๋", "๊น์ฒ ์", "์ด์ํฌ"]
mixed = [1, "hello", 3.14, True]
# Nested list
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Creating with range
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
evens = list(range(0, 11, 2)) # [0, 2, 4, 6, 8, 10]
Indexing and Slicingโ
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ฒด๋ฆฌ", "ํฌ๋", "๋ฉ๋ก "]
# Indexing
print(fruits[0]) # ์ฌ๊ณผ
print(fruits[-1]) # ๋ฉ๋ก
print(fruits[2]) # ์ฒด๋ฆฌ
# Slicing
print(fruits[1:4]) # ['๋ฐ๋๋', '์ฒด๋ฆฌ', 'ํฌ๋']
print(fruits[:3]) # ['์ฌ๊ณผ', '๋ฐ๋๋', '์ฒด๋ฆฌ']
print(fruits[2:]) # ['์ฒด๋ฆฌ', 'ํฌ๋', '๋ฉ๋ก ']
print(fruits[::2]) # ['์ฌ๊ณผ', '์ฒด๋ฆฌ', '๋ฉ๋ก '] (every 2nd item)
print(fruits[::-1]) # ['๋ฉ๋ก ', 'ํฌ๋', '์ฒด๋ฆฌ', '๋ฐ๋๋', '์ฌ๊ณผ'] (reversed)
# 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6
Modifying Listsโ
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ฒด๋ฆฌ"]
# Changing element
fruits[1] = "๋ธ๊ธฐ"
print(fruits) # ['์ฌ๊ณผ', '๋ธ๊ธฐ', '์ฒด๋ฆฌ']
# Changing slice
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [20, 30]
print(numbers) # [1, 20, 30, 5]
# Adding elements
fruits.append("ํฌ๋") # add to end
print(fruits) # ['์ฌ๊ณผ', '๋ธ๊ธฐ', '์ฒด๋ฆฌ', 'ํฌ๋']
fruits.insert(1, "๋ง๊ณ ") # insert at position
print(fruits) # ['์ฌ๊ณผ', '๋ง๊ณ ', '๋ธ๊ธฐ', '์ฒด๋ฆฌ', 'ํฌ๋']
# Extending list
more_fruits = ["๋ฉ๋ก ", "์๋ฐ"]
fruits.extend(more_fruits) # add multiple elements
print(fruits)
# Removing elements
fruits.remove("๋ง๊ณ ") # remove by value
print(fruits)
popped = fruits.pop() # remove and return last element
print(popped) # ์๋ฐ
fruits.pop(0) # remove at position
print(fruits)
del fruits[0] # delete by index
print(fruits)
fruits.clear() # clear all
print(fruits) # []
List Operationsโ
# Concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]
# Repetition
repeated = [0] * 5
print(repeated) # [0, 0, 0, 0, 0]
# Length
print(len([1, 2, 3, 4, 5])) # 5
# Membership
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ฒด๋ฆฌ"]
print("์ฌ๊ณผ" in fruits) # True
print("ํฌ๋" in fruits) # False
print("ํฌ๋" not in fruits) # True
# Count
numbers = [1, 2, 2, 3, 2, 4]
print(numbers.count(2)) # 3
# Find index
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ฒด๋ฆฌ", "๋ฐ๋๋"]
print(fruits.index("๋ฐ๋๋")) # 1 (first occurrence)
Sorting Listsโ
numbers = [3, 1, 4, 1, 5, 9, 2]
# sort() - modifies original
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 9]
numbers.sort(reverse=True)
print(numbers) # [9, 5, 4, 3, 2, 1, 1]
# sorted() - returns new list
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 9]
print(numbers) # [3, 1, 4, 1, 5, 9, 2] (original preserved)
# Sorting strings
words = ["banana", "apple", "cherry"]
words.sort()
print(words) # ['apple', 'banana', 'cherry']
# Reverse
numbers.reverse()
print(numbers)
# Sorting with key function
words = ["apple", "pie", "zoo", "a"]
words.sort(key=len) # by length
print(words) # ['a', 'pie', 'zoo', 'apple']
# Complex sorting
students = [
{"name": "ํ๊ธธ๋", "score": 85},
{"name": "๊น์ฒ ์", "score": 92},
{"name": "์ด์ํฌ", "score": 78}
]
students.sort(key=lambda x: x["score"], reverse=True)
print(students)
List Comprehensionโ
# Basic form
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# if-else
numbers = [1, 2, 3, 4, 5]
result = ["์ง์" if x % 2 == 0 else "ํ์" for x in numbers]
print(result) # ['ํ์', '์ง์', 'ํ์', '์ง์', 'ํ์']
# Nested list
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Flattening
nested = [[1, 2], [3, 4], [5, 6]]
flat = [num for sublist in nested for num in sublist]
print(flat) # [1, 2, 3, 4, 5, 6]
# Practical example
names = ["ํ๊ธธ๋", "๊น์ฒ ์", "์ด์ํฌ"]
upper_names = [name.upper() for name in names]
print(upper_names)
# Conditional transformation
scores = [85, 92, 78, 95, 88]
grades = ["Pass" if score >= 80 else "Fail" for score in scores]
print(grades)
Tupleโ
A tuple is an ordered, immutable collection.
Creating Tuplesโ
# Empty tuple
empty = ()
empty = tuple()
# Tuple with values
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
# Without parentheses
point = 10, 20
print(point) # (10, 20)
# Single element tuple (comma required!)
single = (5,)
not_tuple = (5) # This is just an int
print(type(single)) # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>
# Converting from list
numbers_list = [1, 2, 3]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple) # (1, 2, 3)
Accessing Tuplesโ
colors = ("๋นจ๊ฐ", "์ด๋ก", "ํ๋", "๋
ธ๋")
# Indexing
print(colors[0]) # ๋นจ๊ฐ
print(colors[-1]) # ๋
ธ๋
# Slicing
print(colors[1:3]) # ('์ด๋ก', 'ํ๋')
# Length
print(len(colors)) # 4
# Membership
print("๋นจ๊ฐ" in colors) # True
# Count and index
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2)) # 3
print(numbers.index(3)) # 3
Tuple Operationsโ
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined) # (1, 2, 3, 4, 5, 6)
# Repetition
repeated = (0,) * 5
print(repeated) # (0, 0, 0, 0, 0)
# Comparison
print((1, 2) < (1, 3)) # True (lexicographic)
print((1, 2) == (1, 2)) # True
Tuple Unpackingโ
# Basic unpacking
point = (10, 20)
x, y = point
print(x, y) # 10 20
# Multiple return values
def get_user():
return "ํ๊ธธ๋", 25, "์์ธ"
name, age, city = get_user()
print(name, age, city)
# Extended unpacking (Python 3+)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Swapping values
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# Ignoring values
point = (10, 20, 30)
x, _, z = point
print(x, z) # 10 30
Tuple vs. Listโ
# List: mutable
fruits_list = ["์ฌ๊ณผ", "๋ฐ๋๋"]
fruits_list.append("์ฒด๋ฆฌ") # โ
print(fruits_list)
# Tuple: immutable
fruits_tuple = ("์ฌ๊ณผ", "๋ฐ๋๋")
# fruits_tuple.append("์ฒด๋ฆฌ") # โ AttributeError
# Tuples are faster and more memory efficient
import sys
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3, 4, 5)
print(sys.getsizeof(list_data)) # 104
print(sys.getsizeof(tuple_data)) # 88
# Tuples can be used as dictionary keys
locations = {
(0, 0): "์์ ",
(1, 0): "๋์ชฝ",
(0, 1): "๋ถ์ชฝ"
}
print(locations[(0, 0)]) # ์์
# Lists cannot
# locations = {[0, 0]: "์์ "} # โ TypeError
Practical Examplesโ
Student Grade Managementโ
# Student information (tuple for immutable data)
students = [
("ํ๊ธธ๋", 85, 90, 88),
("๊น์ฒ ์", 92, 88, 95),
("์ด์ํฌ", 78, 85, 82)
]
# Calculate average
def calculate_average(scores):
name, *grades = scores
avg = sum(grades) / len(grades)
return name, avg
for student in students:
name, avg = calculate_average(student)
print(f"{name}: Average {avg:.1f} points")
# Best student
best_student = max(students, key=lambda x: sum(x[1:]))
print(f"Highest score: {best_student[0]}")
To-Do Listโ
class TodoList:
def __init__(self):
self.tasks = []
def add(self, task):
"""Add a task"""
self.tasks.append({"task": task, "done": False})
print(f"'{task}' added")
def complete(self, index):
"""Complete a task"""
if 0 <= index < len(self.tasks):
self.tasks[index]["done"] = True
print(f"'{self.tasks[index]['task']}' completed!")
def remove(self, index):
"""Remove a task"""
if 0 <= index < len(self.tasks):
task = self.tasks.pop(index)
print(f"'{task['task']}' removed")
def show(self):
"""Display task list"""
if not self.tasks:
print("No tasks!")
return
print("\n=== To-Do List ===")
for i, item in enumerate(self.tasks):
status = "โ" if item["done"] else " "
print(f"{i+1}. [{status}] {item['task']}")
# Usage example
todo = TodoList()
todo.add("Python ๊ณต๋ถํ๊ธฐ")
todo.add("์ด๋ํ๊ธฐ")
todo.add("์ฑ
์ฝ๊ธฐ")
todo.show()
todo.complete(0)
todo.show()
Data Analysisโ
# Sales data (product name, quantity, price)
sales = [
("๋
ธํธ๋ถ", 5, 1200000),
("๋ง์ฐ์ค", 30, 25000),
("ํค๋ณด๋", 15, 85000),
("๋ชจ๋ํฐ", 8, 350000)
]
# Calculate total revenue
def calculate_revenue(sales_data):
total = 0
for product, quantity, price in sales_data:
revenue = quantity * price
total += revenue
print(f"{product}: {revenue:,}์")
return total
print("\n=== Revenue by Product ===")
total_revenue = calculate_revenue(sales)
print(f"\nTotal Revenue: {total_revenue:,}์")
# Best selling product
best_seller = max(sales, key=lambda x: x[1])
print(f"\nBest seller: {best_seller[0]} ({best_seller[1]}๊ฐ)")
# Sort by revenue
sorted_sales = sorted(sales, key=lambda x: x[1] * x[2], reverse=True)
print("\n=== Revenue Ranking ===")
for rank, (product, qty, price) in enumerate(sorted_sales, 1):
print(f"{rank}. {product}: {qty * price:,}์")
Coordinate Managementโ
# 2D coordinates
points = [(0, 0), (3, 4), (1, 1), (5, 12)]
# Calculate distance from origin
def distance_from_origin(point):
x, y = point
return (x**2 + y**2) ** 0.5
# Calculate and sort distances
distances = [(point, distance_from_origin(point)) for point in points]
distances.sort(key=lambda x: x[1])
print("=== Distance from Origin ===")
for point, dist in distances:
print(f"{point}: {dist:.2f}")
# Farthest point
farthest = max(points, key=distance_from_origin)
print(f"\nFarthest point: {farthest}")
Frequently Asked Questionsโ
Q1. When should I use lists vs. tuples?โ
A: Decide based on mutability needs
# List: mutable data
shopping_cart = ["์ฌ๊ณผ", "๋ฐ๋๋"]
shopping_cart.append("์ฐ์ ") # cart changes frequently
# Tuple: immutable data
birth_date = (1990, 5, 15) # birthdate is fixed
coordinates = (37.5665, 126.9780) # coordinates are fixed
Q2. How do I copy a list?โ
A: Distinguish between shallow and deep copy
original = [1, 2, 3]
# Reference copy (same object)
ref = original
ref.append(4)
print(original) # [1, 2, 3, 4] - original also changed!
# Shallow copy (new object)
shallow = original.copy()
# or
shallow = original[:]
# or
shallow = list(original)
shallow.append(5)
print(original) # [1, 2, 3, 4] - original preserved
# Deep copy (nested list)
import copy
nested = [[1, 2], [3, 4]]
deep = copy.deepcopy(nested)
deep[0].append(3)
print(nested) # [[1, 2], [3, 4]] - original preserved
Q3. How do I check if a list is empty?โ
A: There are several ways
my_list = []
# Method 1: Check length
if len(my_list) == 0:
print("Empty")
# Method 2: Boolean conversion (Pythonic!)
if not my_list:
print("Empty")
# Method 3: Comparison
if my_list == []:
print("Empty")
Q4. What should I watch out for when initializing multi-dimensional lists?โ
A: Be careful with reference copies
# โ Wrong way
matrix = [[0] * 3] * 3
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] - All rows are the same!
# โ
Correct way
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]] - Normal
Next Stepsโ
You've mastered lists and tuples!
Key Takeaways:
โ
List: mutable, various methods
โ
Tuple: immutable, fast and safe
โ
Indexing, slicing, unpacking
โ
List comprehension
โ
Practical use cases
Next Step: Learn more about collections in Dictionaries and Sets!