Tuesday, August 29, 2017

Python


Python Practice


Iterate over a list in Python

for val in a:
    print(val)

Using for Loop with range()

n = len(a)
 
# Iterates over the indices from 0 to n-1 (i.e., 0 to 4)
for i in range(n):
    print(a[i])

Using while Loop

# Start from the first index
i = 0
 
# The loop runs till the last index (i.e., 4)
while i < len(a):
    print(a[i])
    i += 1

Using enumerate()

# Here, i and val reprsents index and value respectively
for i, val in enumerate(a):
    print (i, val)

Using List Comprehension

left = 0
right = 2
pp = [num_val for i, num_val in enumerate(a) if i >= left and i <= right]

9 comments:

  1. Good to know about the email list business. I was looking for such a service f or a long time to grow my local business but the rates that other companies were offering were not satisfactory. Thanks for sharing the recommendations in this post.HADOOP Training Institutes in Bangalore

    ReplyDelete
  2. Really a awesome blog for the freshers. Thanks for posting the information.python training in bangalore

    ReplyDelete
  3. This is a really helpful collection of Python iteration techniques! The different approaches—using for loops, range(), while loops, enumerate(), and list comprehension—give learners a comprehensive understanding of how to work with lists in Python. Each method has its own use case, and seeing them side by side makes it easy to choose the right approach. For those building programming foundations, these fundamental patterns are essential before moving on to more complex topics like data science and AI. I've been researching Gen AI and Agentic AI course with placement in Electronic City to understand how Python is used in AI development. Thanks for sharing this practical Python tutorial!

    ReplyDelete