Home > Back-end >  How to iterate all item at once in python list?
How to iterate all item at once in python list?

Time:10-03

let's say i have list

strs = ["dog","racecar","car"]

when I = 0 , then I want

d,r,c

when I = 1, then I want

do,ra,ca

when I = 2, then I want

dog,rac,car

like that How can i do this ?

CodePudding user response:

First Part

1.

strs = ["dog","racecar","car"]

l = 0
for a in strs:
    print(a[:l 1],end=' ')

Output

d r c 

Explanation.

  1. First loop through all the strings in the list.
  2. Then print the string only to the l index, I use l 1 because the end is excluded.
  3. Means If you run print('hello'[0:3]) it will give all strings to the index 0 to 2 not 3/
  4. set end=' ' so it will not ends with a new line.

2.

strs = ["dog","racecar","car"]

l = 0
lst = [a[:l 1] for a in strs]
print(*lst) # here *lst is same as print(lst[0],lst[1],...,lst[n]) 

Output

d r c 

Second part

1.

strs = ["dog","racecar","car"]

for l in range(min(len(a) for a in strs)):
    for s in strs:
        print(s[:l 1],end=' ')

    print()

Output

d r c 
do ra ca 
dog rac car

2.

strs = ["dog","racecar","car"]


for l in range(min(len(a) for a in strs)):
    print(*[s[:l 1] for s in strs])

Output

d r c 
do ra ca 
dog rac car


Explanation for min(len(a) for a in strs)

  1. Here inner comprehension(len(a) for a in strs) generates a list with the value as the length of the string inside the list.
  2. Then min(len(a) for a in strs) returns the lowest number from the above list.

I hope my explanation is clear. If not please ask me in the comments.

CodePudding user response:

First you need to find the minimum length and then loop through each size up to that length.

strs = ["dog","racecar","car"]

for l in range(min(len(w) for w in strs)):
    print(",".join(s[:l 1] for s in strs))

CodePudding user response:

strs = ["dog","racecar","car"]
def func(arr,n):
    w=""
    for i in range(len(arr)):
        if n<=len(arr[0])-1:
            w =(arr[i])[0:n] " "
        else:
            w =arr[i] " "
    return w;
print(func(strs,2))

Keep on adding sliced portions of each string via loops,If the value of "l" [the variable you used to refer to the final pos] were to exceed the length of the string, the string would be added as a whole. (at least that's how I would handle that case).

  • Related