Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python List Operations: Iteration, Numerical Lists, and Slicing

Tech 2

Iterating Through an Entire List

The For Loop

You can use a for loop to iterate through every element in a list.

names = ['Huang Wei', 'nB', 'apple', 'DDD']
for item in names:
    print(item)
    print(type(item))
print(item)  # This prints the last item after the loop finishes

Output:

Huang Wei
<class 'str'>
nB
<class 'str'>
apple
<class 'str'>
DDD
<class 'str'>
DDD

Note: The for loop only repeats the indented statements immediate folowing it. The colon (:) at the end of the for statement tells Python that the next line is the first line of the loop body.

Creating Numerical Lists

1. The range() Function

The range() function can be used to easily generate a sequence of numbers.

for num in range(1, 6):
    print(num, end="\t")

Output: 1 2 3 4 5

Note: The number 6 is not printed. The range(start, stop) function counts from start up to, but not including, stop.

  • range(stop): Starts from 0. Example: range(6) returns 0, 1, 2, 3, 4, 5.
  • range(start, stop, step): Alllows specifying a step size. Example: range(1, 6, 2) returns 1, 3, 5.

2. Creating a List with range()

You can convert the output of range() directly into a list using the list() function.

numbers = list(range(1, 6, 2))
print(numbers)

Output: [1, 3, 5]

Example: How too create a list containing the squares of numbers from 1 to 10.

squares = []
for i in range(1, 11):
    squares.append(i ** 2)
print(squares)

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3. Simple Statistical Operations on Numerical Lists

You can use built-in functions like min(), max(), and sum() on lists of numbers.

num_list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print(min(num_list))
print(max(num_list))
print(sum(num_list))

4. List Comprehensions

A list comprehension combines the for loop and the code for creating new elements into a single line, automatically appending each new element.

squares = [value ** 2 for value in range(1, 11)]
print(squares)

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Note: The for statement inside the list comprehension does not end with a colon.

Working with Parts of a List

1. Slicing

To create a slice, you specify the index of the first element you want and the index of the element after the last element you want. The slice stops before raeching the second index.

names = ['Huang Wei', 'nB', 'apple', 'DDD']
print(names[0:3])

Output: ['Huang Wei', 'nB', 'apple']

Corresponding Indices: 0, 1, 2

print(names[-3:])

Output: ['nB', 'apple', 'DDD']

Explanation: The slice [-3:] starts from the third element from the end and goes to the end of the list.

Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.