How to use one line for loop in Python

6 Answers

0 votes
lst = ['python', 'c', 'c++', 'c#', 'java']

for s in lst: print(s)




     
     
'''
run:
     
python
c
c++
c#
java
  
'''

 



answered Apr 23, 2021 by avibootz
0 votes
dict = {'python': 5, 'php': 3, 'java': 9, 'c++': 1, 'c':8}

for key, val in dict.items(): print(key, val)




     
     
'''
run:
     
python 5
php 3
java 9
c++ 1
c 8
  
'''

 



answered Apr 23, 2021 by avibootz
0 votes
for i in range(1, 10): print(i)



     
     
'''
run:
     
1
2
3
4
5
6
7
8
9
  
'''

 



answered Apr 23, 2021 by avibootz
0 votes
lst = [1, 2, 3, 4, 5]

lst = [x**2 for x in lst]

print(lst)



     
     
'''
run:
     
[1, 4, 9, 16, 25]
  
'''

 



answered Apr 23, 2021 by avibootz
0 votes
lst = [1, 2, 3, 4, 5, 6, 7]

lst = [x for x in lst if x%2 == 0]

print(lst)



     
     
'''
run:
     
[2, 4, 6]
  
'''

 



answered Apr 23, 2021 by avibootz
0 votes
lst = [1, 2, 3, 4, 5, 6, 7]

lst = [x + 10 if x % 2 == 0 else x for x in lst]

print(lst)



     
     
'''
run:
     
[1, 12, 3, 14, 5, 16, 7]
  
'''

 



answered Apr 23, 2021 by avibootz

Related questions

1 answer 178 views
1 answer 191 views
1 answer 193 views
1 answer 217 views
1 answer 205 views
1 answer 153 views
...