Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop + add something
#1
Hello,

I am relevant new to the language Python. However, I can code in PHP and VBA and other languages so I am not a total beginner.


I am wondering how I can create a Loop that goes one by one

So Instead of just printing out the whole loop as this one does:
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
  print(x) 
How do I do so it does like this:
cars = ["Ford", "Volvo", "BMW"]
for r = 1 to 3

variable(r) = "The car cars(r) has been sold"

Next r


Print("out all variables (should be 3 if the loop finnish)")
Results:
The car Ford has been sold
The car Volvo has been sold
The car BMW has been sold


Thanks in advance!
Reply
#2
cars = ["Ford", "Volvo", "BMW"]

for r in range(3):
    print(f"The car {cars[r]} has been sold")
Output:
The car Ford has been sold The car Volvo has been sold The car BMW has been sold
Reply
#3
Nice, thanks! How do I do it more dynamic, instead of writing:

for r in range(3):
change it to more dynamic such as it counts the array inputs?

For instance;

for r in range(n):
Where n = the total in the array. Reason I want to do it is if the array is very long I do not need to count 1 by 1.
Reply
#4
I found it, thanks man!

cars = ["Ford", "Volvo", "BMW","test"]


for r in range(len(cars)):
 print(f"The car {cars[r]} has been sold")
Follow up question though, I want to show that "Ford = 1" and then "Volvo" = 2 etc.:


cars = ["Ford", "Volvo", "BMW","test"]


for r in range(len(cars)):

    # print(f"This should be in {r}") -- This code does not work but you see what I try to do?
 print(f"The car {cars[r]} has been sold")
Should give:

"This should be 1: The car Ford has been sold"
"This should be 2: The car Volvo has been sold"
"This should be 3: The car BMW has been sold"
Reply
#5
Is this what you're looking for?
car_list = ['Ford', 'Volvo', 'BMW']

for car in car_list :
	print (f'The {car} has been sold.')

print (f'There were {len (car_list)} cars sold.')
Output:
The Ford has been sold. The Volvo has been sold. The BMW has been sold. There were 3 cars sold.
Reply
#6
(Jun-23-2022, 09:12 PM)Matheus Wrote: I found it, thanks man!
No,dont do this.
Never use "for i in range(len(sequence)):"
Just iterate over the list.
cars = ["Ford", "Volvo", "BMW"]
for car in cars:
    print(f"The car {car} has been sold")
The car Ford has been sold
The car Volvo has been sold
The car BMW has been sold
If later some time need to do something with index,then use enumerate() .
cars = ["Ford", "Volvo", "BMW"]
for index, car in enumerate(cars, start=1):
    print(f"The car{index} {car} has been sold")
Output:
The car1 Ford has been sold The car2 Volvo has been sold The car3 BMW has been sold
Reply
#7
Thanks. How come not to use "len" in that way?
Reply
#8
(Jun-23-2022, 09:37 PM)Matheus Wrote: Thanks. How come not to use "len" in that way?
There are objects which does not have knowledge about len, but are iterable. For example, iterating over a file-object. As a result, you get line by line, but the iterator does not know how many lines, so the len function could not work on a file object.

All sequences (bytes, str, tuple, list), all collections (set, frozenset) and mappings (dict), Generators and Iterators support iteration, but not all share the same behavior of index access. On collections, you can't get the 10th element. You can get 10 unique elements from a set in a "random" order with the pop method or with iteration.

All share the same, all support iteration.
If you have a list with cars and want to print the cars, then iterate over cars.
If you want to count during iteration, then use enumerate. It takes an iterable and the second argument is the start.

Iteration is strong in Python and used in many places. Things like range(len(something)) are antipatterns because you take the flexibility away.

Bad example (cars is now a set):
# cars is now a set
# a set has unique elements and no order
# no index access
# but you can still iterate over them
cars = {"Ford", "Volvo", "BMW","test"}
 

# this part has not been changed
for r in range(len(cars)):
    print(f"The car {cars[r]} has been sold")
Error:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [1], in <cell line: 5>() 4 # this part has not been changed 5 for r in range(len(cars)): ----> 6 print(f"The car {cars[r]} has been sold") TypeError: 'set' object is not subscriptable
A set has no order, so there is no index access.
(Maybe in future)


Pythonic way:
# natural words which explain the meaning
unique_cars = {"Ford", "Volvo", "BMW"}

for car in unique_cars:
    print(f"The car {car} has been sold")
The car BMW has been sold
The car Volvo has been sold
The car Ford has been sold
No Exception.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#9
Python only pretends to have lists. In fact, internally, Python has integer indexed arrays, just the same as PHP.

Knowing a list is in fact an integer indexed array, the index beginning with zero, why not make use of that fact and the relationship of the length to the indexing? Simple and useful!

Because you can't do that with sets doesn't seem like much of a reason to abandon that approach with lists and plump for enumerate, when the indexing is already there.

I don't know how Python treats sets internally, but, probably, the string within the brackets is split on the commas, giving a list-like object, which can then be iterated over. Somehow Python has to access each element individually.

Also, for any given set, say, data = {7058, 7059, 7072, 7074, 7076}, I can immediately create a list: mylist = list(data)
Reply
#10
(Jun-23-2022, 11:04 PM)Pedroski55 Wrote: Knowing a list is in fact an integer indexed array, the index beginning with zero, why not make use of that fact and the relationship of the length to the indexing? Simple and useful!
No,it's just stupid if think about it.
Old but good Loop Like A Native
Quote:Python gives us a much more natural way to loop over the values in my_list.
Why are we talking about integers? This is like a Rube Goldberg machine.
We set up a mechanism to give us integers, when we don’t want the integers at all,
so the first thing we do with each integer is turn it into a list element.
We might has well have written,the boot kicks the ball into the net, which tips the watering can...
Rather than iterating over indexes, and using the index i to get the value we really want from the list, we can simply loop over the values directly
# The Rube Goldberg machine way
cars = ["Ford", "Volvo", "BMW"]
for car in range(len(cars)):
    print(f"The car {cars[car]} has been sold")
Output:
The car Ford has been sold The car Volvo has been sold The car BMW has been sold

# Simple as this
cars = ["Ford", "Volvo", "BMW"]
for car in cars:
    print(f"The car {car} has been sold")
Output:
The car Ford has been sold The car Volvo has been sold The car BMW has been sold
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020