How to implement an infinite element list in Python, and an infinite element list in python

Source: Internet
Author: User
Tags python list

How to implement an infinite element list in Python, and an infinite element list in python

The example in this article describes how to implement the infinite element list in Python. The specific implementation can be completed using Yield.

The following two sample codes use the Python Yield generator to implement a simple list of infinite elements.

1. incrementing infinite list

The Code is as follows:

def increment(): i = 0 while True:  yield i  i += 1 for j in increment(): print i if (j > 10) : break

2. Fibonacci unlimited list

The Code is as follows:

def fibonacci(): i = j = 1 while True:  result, i, j = i, j, i + j  yield result for k in fibonacci(): print k if (k > 100) : break

Five Elements in python List a are obtained by user input.

# Coding = UTF-8
MyList = []
For I in range (5)
MyList [I] = input () # each element is a string and needs to be converted to another type.
Print myList

Adding elements to the list by python

Input is the data input command in Python3; In Python2, the data input from the console is raw_input;
As follows:

Python 3.2.3 (default, Feb 20 2013, 17:02:41)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> A = []
>>> For I in range (3 ):
... A. append (input ("Enter :"))
...
Enter: 1 2 3
Enter: 3 4 5
Enter: 5 6 7
>>>
['1 2 3', '3 4 5', '5 6 7']
>>>

Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> A = []
>>> For I in range (3 ):
... A. append (raw_input ("Enter :"))
...
Enter: 1 2 3
Enter: 4 5 6
Enter: 7 8 9
>>>
>>>
['1 2 3', '4 5 6', '7 8 9']
>>>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.