Python Core Concepts: Iteration, Slicing, and Turtle Graphics
Negative Indexing and List Slicing
Python sequences support negative indexing, allowing access to elements from the end. For instance, an index of -2 retrieves the penultimate item.
dataset = [10, 20, 30, 40, 50]
penultimate = dataset[-2] # Retrieves 40
Slicing extracts sub-sequences using the syntax [start:stop:step]. The start is inclusive, stop is exclusive, and step defaults to 1.
items = [1, 2, 3, 4, 5]
print(items[1:4]) # [2, 3, 4]
print(items[-3:]) # [3, 4, 5]
print(items[::2]) # [1, 3, 5]
text = "Hello, World!"
print(text[7:]) # World!
Loops and Iteration
The for loop iterates over sequences or generated ranges. The range() function yields a sequence of numbers, while lists can be traversed directly.
# Iterating through a generated range
for idx in range(15):
print(idx)
# Traversing a collection
vehicles = ["car", "bike", "train"]
for vehicle in vehicles:
print(vehicle)
Transformations can be applied directly using list comprehensions.
values = [1, 2, 3, 4]
squared = [v**2 for v in values]
The map() Function
map() applies a given function to all items in an input iterable, returning a map object. Wrapping it with list() materializes the results.
# Converting integers to strings
integers = [5, 10, 15]
str_list = list(map(str, integers))
# Cubing elements
nums = [1, 2, 3]
cubed = list(map(lambda x: x ** 3, nums))
# Multiplying corresponding elements from two lists
set_a = [2, 4, 6]
set_b = [10, 20, 30]
products = list(map(lambda a, b: a * b, set_a, set_b))
Iterators
An iterator is an object that implements __iter__() and __next__(), enabling sequential traversal of data without exposing the underlying representation.
Graphical Drawing with Turtle
The turtle module provides vector graphics drawing capabilities. Initialize the drawing environment and cursor as follows:
import turtle
import random
canvas = turtle.Screen()
canvas.bgcolor("black")
cursor = turtle.Turtle()
cursor.speed(0)
cursor.width(2)
turtle.colormode(255)
Define functions to control cursor movement, appearance, and drawing actions:
def advance():
cursor.forward(15)
def retreat():
cursor.backward(15)
def rotate_left():
cursor.left(15)
def rotate_right():
cursor.right(15)
def randomize_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
cursor.pencolor(r, g, b)
def thicken_line():
current = cursor.width()
cursor.width(current + 1)
def thin_line():
current = cursor.width()
if current > 1:
cursor.width(current - 1)
Bind these functions to keyboard events to enable interactive drawing:
canvas.listen()
canvas.onkey(advance, "w")
canvas.onkey(retreat, "s")
canvas.onkey(rotate_left, "a")
canvas.onkey(rotate_right, "d")
canvas.onkey(randomize_color, "c")
canvas.onkey(thicken_line, "Up")
canvas.onkey(thin_line, "Down")
To generate automated geometric patterns, such as a multi-colored spiral, loop the movement and rotation commands:
for step in range(300):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
cursor.pencolor(r, g, b)
cursor.forward(step * 1.5)
cursor.right(91)
Manipulate cursor visibility and positional attributes programmatically:
cursor.hideturtle()
canvas.exitonclick()
# Positioning
cursor.goto(50, -50)
cursor.home() # Returns to (0, 0)
# Orientation
cursor.setheading(90) # Faces north (upwards)