Home > Backend Development > Python Tutorial > Mastering Python Lists: Essential Techniques You Need to Know

Mastering Python Lists: Essential Techniques You Need to Know

Patricia Arquette
Release: 2024-11-12 22:28:02
Original
259 people have browsed it

Mastering Python Lists: Essential Techniques You Need to Know

For

simple for

This will loop through the list and each element of the list will be available as a variable in every iteration. This is widely used when there is a need to go over all the elements of the list.

operating_systems = ["windows", "mac", "linux"]
for os in operating_systems:
    print(os)`

Copy after login
# Output
windows
mac
linux
Copy after login

for and range

When there is need for accessing based on index and index value is required.

operating_systems = ["windows", "mac", "linux"]
for i in range(len(operating_systems)):
    print(f"Index {i}: {operating_systems[i]}")
Copy after login
# Output
Index 0: windows
Index 1: mac
Index 2: linux
Copy after login

for and enumerate

This is an elegant way, if you need both index and the value

operating_systems = ["windows", "mac", "linux"]
for index, os in enumerate(operating_systems):
    print(f"Index is {index} and value is {os}")
Copy after login
# Output
Index is 0 and value is windows
Index is 1 and value is mac
Index is 2 and value is linux
Copy after login

While

simple while

operating_systems = ["windows", "mac", "linux"]
i = 0 # Inital condition, required to start
while i < len(operating_systems):
    print(f"While looping {i} got the value {operating_systems[i]}")
    i = i + 1 # This is very important, dont forget about infinite loops
Copy after login
# Output
While looping 0 got the value windows
While looping 1 got the value mac
While looping 2 got the value linux
Copy after login

Iterator

Gives fine control over when to move the iterator forward, though we have to rely on the StopIteration to check if the end is reached.

operating_systems = ["windows", "mac", "linux"]
iterator = iter(operating_systems)
while True:
    try:
        os = next(iterator)
        print(f"Consumed form iterator {os}")
    except StopIteration:
        print("Consumed all from iterator")
        break
Copy after login
# Output
Consumed form iterator windows
Consumed form iterator mac
Consumed form iterator linux
Consumed all from iterator
Copy after login
# Hack to avoid StopIteration
iterator = iter(operating_systems)
end_of_list = object()
reached_end = False
while not reached_end:
    os = next(iterator, end_of_list)# a predefined object as end of the list
    if os != end_of_list:
        print(os)
    else:
        reached_end = True
Copy after login

List comprehension

When transformation is required

operating_systems = ["windows", "mac", "linux"]
os_uppercase = [os.upper() for os in operating_systems]
print(os_uppercase) 
Copy after login
# Output
['WINDOWS', 'MAC', 'LINUX']
Copy after login

Cycling

When cycling through a list is require. Use with proper boundary condition to break the loop

import itertools
operating_systems = ["windows", "mac", "linux"]
for item in itertools.cycle(operating_systems):  
    print(item)
# Infinite cycling loopmake sure to have proper boundary condition to break
Copy after login
# Output
windows
mac
linux
windows
mac
linux
windows
mac
linux
windows
mac
linux
windows ....... Infinite loop
Copy after login

Over multiple lists

Simultaneously loop over multiple lists. Note the output if the list sizes are different.

operating_systems = ["windows", "mac", "linux"]
mobile_operating_systems = ["android", "ios"]

for os, mobile_os in zip(operating_systems,mobile_operating_systems):
    print(os, mobile_os)
Copy after login
# Output
windows android
mac ios
Copy after login

Loop in reverse

operating_systems = ["windows", "mac", "linux"]
for reversed_os in reversed(operating_systems):
    print(reversed_os)
Copy after login
# Output
linux
mac
windows
Copy after login

The above is the detailed content of Mastering Python Lists: Essential Techniques You Need to Know. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template