Python learning while loop list

Hello everyone, I am having a hard time understanding while loop when it comes to a list.

Using the while loop:

List all the presidents whose names do not contain the letter ‘w’

listUSPresidents=[“George Washington”,“John Adams”,“Thomas Jefferson”,“James Madison”,“James Monroe”,“John Quincy Adams”,“Andrew Jackson”,“Martin Van Buren”,“William H. Harrison”,“John Tyler”,“James K. Polk”,“Zachary Taylor”,“Millard Fillmore”,“Franklin Pierce”,“James Buchanan”,“Abraham Lincoln”,“Andrew Johnson”,“Ulysses S. Grant”,“Rutherford B. Hayes”,“James A. Garfield”,“Chester A. Arthur”,“Grover Cleveland”,“Benjamin Harrison”,“Grover Cleveland”,“William McKinley”,“Theodore Roosevelt”,“William H. Taft”,“Woodrow Wilson”,“Warren G. Harding”,“Calvin Coolidge”,“Herbert Hoover”,“Franklin D. Roosevelt”,“Harry S. Truman”,“Dwight D. Eisenhower”,“John F. Kennedy”,“Lyndon B. Johnson”,“Richard M. Nixon”,“Gerald R. Ford”,“Jimmy Carter”,“Ronald Reagan”,“George H. W. Bush”,“Bill Clinton”,“George W. Bush”,“Barack Hussein Obama”,“Donald J. Trump”]

Can any one help me understand how to write this code? I am using Jupyter to execute it.

Thank you very much!

if want to retrieve irrespective of the case of ‘w’, maybe,

l = ['abc', 'wabc', 'Wabc']
[i for i in l if 'w' not in i.lower()]

similar could be done using a while loop

Thank you for taking the time to go over this, I am getting the list of Presidents now with your provided example. I wonder how I can nest this into a while loop?

Thank you :)!

sorry I pretty much never use while loop, I might as well be fine if it gets deprecated in the future.

Here’s an example that may help you understand how to use a while-loop with a list. Suppose you want to print each element of a list my_list.

# using a for-loop
for e in my_list:

# using a while-loop
i = 0
while i < len(my_list):
    i += 1

Here is another way how to use while for this kind of task. This one is almost the same way how the for loop works. The biggest difference is that my_list cannot contain None (it would prematurely end the loop).

my_list = ['abc', 'wabc', 'Wabc']
my_list_iter = iter(my_list)
while (item := next(my_list_iter, None)) is not None:
1 Like