Enumerate() in Python

Enumerate() in Python

In this article, we will talk how to use the Python's `enumerate()` function. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

enumerate() is a built-in function in Python that allows you to have an automatic counter while looping over iterables. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task.

Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Python enumerate() Function

The enumerate() function takes the following form:

enumerate(iterable, start=0)

The function accepts two arguments:

  • iterable - An object that supports iteration.
  • start - The number from which the counter starts. This argument is optional. By default, counter starts from 0.

enumerate() returns an enumerate object on which you can call the __next__() (or next() in Python 2) method to get a tuple containing a count and the current value of the iterable.

Here is an example of how to create a list of tuples using list() and how to loop over an iterable:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions))

for index, value in enumerate(directions): 
    print("{}: {}".format(index, value))

[(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]

0: north
1: east
2: south
3: west

If the zero-based indexing doesn't work for you, choose another starting index for the enumeration:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions, 1))

[(1, 'north'), (2, 'east'), (3, 'south'), (4, 'west')]

The enumerate() function works on any iterable object. An iterable is a container that can be iterated over. Putting it in simple words, it means an object that you can loop over with a for loop. Most of the built-in objects in Python like strings, lists, and tuples are iterables.

Write More Pythonic Code with enumerate()

Python's for loop is totally different from the traditional C-style for loop which is available in many programming languages. The for loop in Python is equivalent to other languages’ foreach loop.

A common technique used by new Python developers to get the corresponding index when dealing with iterables is to use either the range(len(...)) pattern or set and increment a counter:

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for i in range(len(planets)):
    print("Planet {}: {}".format(i, planets[i]))

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
i = 0
for planet in planets:
    print("Planet {}: {}".format(i, planet))
    i += 1

The loops above can be rewritten in more idiomatic way using enumerate():

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for index, value in enumerate(planets): 
    print("Planet {}: {}".format(index, value))

All methods will produce the same output:

Planet 0: Mercury
Planet 1: Venus
Planet 2: Earth
Planet 3: Mars
Planet 4: Jupiter
Planet 5: Saturn
Planet 6: Uranus
Planet 7: Neptune

Conclusion

In this article, we have shown you how to use the Python's enumerate() function.

Thank you for reading !

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

Learn Python Tutorial from Basic to Advance

Learn Python Tutorial from Basic to Advance

Basic programming concept in any language will help but not require to attend this tutorial

Description
Become a Python Programmer and learn one of employer's most requested skills of 21st century!

This is the most comprehensive, yet straight-forward, course for the Python programming language on Simpliv! Whether you have never programmed before, already know basic syntax, or want to learn about the advanced features of Python, this course is for you! In this course we will teach you Python 3. (Note, we also provide older Python 2 notes in case you need them)

With over 40 lectures and more than 3 hours of video this comprehensive course leaves no stone unturned! This course includes tests, and homework assignments as well as 3 major projects to create a Python project portfolio!

This course will teach you Python in a practical manner, with every lecture comes a full coding screencast and a corresponding code notebook! Learn in whatever manner is best for you!

We will start by helping you get Python installed on your computer, regardless of your operating system, whether its Linux, MacOS, or Windows, we've got you covered!

We cover a wide variety of topics, including:

Command Line Basics
Installing Python
Running Python Code
Strings
Lists
Dictionaries
Tuples
Sets
Number Data Types
Print Formatting
Functions
Scope
Built-in Functions
Debugging and Error Handling
Modules
External Modules
Object Oriented Programming
Inheritance
Polymorphism
File I/O
Web scrapping
Database Connection
Email sending
and much more!
Project that we will complete:

Guess the number
Guess the word using speech recognition
Love Calculator
google search in python
Image download from a link
Click and save image using openCV
Ludo game dice simulator
open wikipedia on command prompt
Password generator
QR code reader and generator
You will get lifetime access to over 40 lectures.

So what are you waiting for? Learn Python in a way that will advance your career and increase your knowledge, all in a fun and practical way!

Basic knowledge
Basic programming concept in any language will help but not require to attend this tutorial
What will you learn
Learn to use Python professionally, learning both Python 2 and Python 3!
Create games with Python, like Tic Tac Toe and Blackjack!
Learn advanced Python features, like the collections module and how to work with timestamps!
Learn to use Object Oriented Programming with classes!
Understand complex topics, like decorators.
Understand how to use both the pycharm and create .py files
Get an understanding of how to create GUIs in the pycharm!
Build a complete understanding of Python from the ground up!

Best Way to Learn Python Programming Language | Python Tutorial

Best Way to Learn Python Programming Language | Python Tutorial

Worried that you have no experience in handling Python? Don’t! Python programming language teaching from Simpliv puts you right there to be able to write Python programs with ease. Place object-oriented programing in a Python context and use Python to perform complicated text processing.

Description
A Note on the Python versions 2 and 3: The code-alongs in this class all use Python 2.7. Source code (with copious amounts of comments) is attached as a resource with all the code-alongs. The source code has been provided for both Python 2 and Python 3 wherever possible.

What's Covered:

Introductory Python: Functional language constructs; Python syntax; Lists, dictionaries, functions and function objects; Lambda functions; iterators, exceptions and file-handling
Database operations: Just as much database knowledge as you need to do data manipulation in Python
Auto-generating spreadsheets: Kill the drudgery of reporting tasks with xlsxwriter; automated reports that combine database operations with spreadsheet auto-generation
Text processing and NLP: Python’s powerful tools for text processing - nltk and others.
Website scraping using Beautiful Soup: Scrapers for the New York Times and Washington Post
Machine Learning : Use sk-learn to apply machine learning techniques like KMeans clustering
Hundreds of lines of code with hundreds of lines of comments
Drill #1: Download a zip file from the National Stock Exchange of India; unzip and process to find the 3 most actively traded securities for the day
Drill #2: Store stock-exchange time-series data for 3 years in a database. On-demand, generate a report with a time-series for a given stock ticker
Drill #3: Scrape a news article URL and auto-summarize into 3 sentences
Drill #4: Scrape newspapers and a blog and apply several machine learning techniques - classification and clustering to these
Using discussion forums

Please use the discussion forums on this course to engage with other students and to help each other out. Unfortunately, much as we would like to, it is not possible for us at Loonycorn to respond to individual questions from students:-(

We're super small and self-funded with only 2 people developing technical video content. Our mission is to make high-quality courses available at super low prices.

The only way to keep our prices this low is to NOT offer additional technical support over email or in-person. The truth is, direct support is hugely expensive and just does not scale.

We understand that this is not ideal and that a lot of students might benefit from this additional support. Hiring resources for additional support would make our offering much more expensive, thus defeating our original purpose.

It is a hard trade-off.

Thank you for your patience and understanding!

Who is the target audience?

Yep! Folks with zero programming experience looking to learn a new skill
Machine Learning and Language Processing folks looking to apply concepts in a full-fledged programming language
Yep! Computer Science students or software engineers with no experience in Java, but experience in Python, C++ or even C#. You might need to skip over some bits, but in general the class will still have new learning to offer you :-)
Basic knowledge
No prior programming experience is needed :-)
The course will use a Python IDE (integrated development environment) called iPython from Anaconda. We will go through a step-by-step procedure on downloading and installing this IDE.
What will you learn
Pick up programming even if you have NO programming experience at all
Write Python programs of moderate complexity
Perform complicated text processing - splitting articles into sentences and words and doing things with them
Work with files, including creating Excel spreadsheets and working with zip files
Apply simple machine learning and natural language processing concepts such as classification, clustering and summarization
Understand Object-Oriented Programming in a Python context