creating lists with loops in python

  • Last Update :
  • Techknowledgy :

July 12, 2021July 12, 2021

Simple python example code.

list_1 = list()

for x in range(5):
   list_1.append(x)

print(list_1)

Another example using map() Objects

txns = [5, 20, 50, 40]
TAX_RATE = .08

def get_price_with_tax(txn):
   return txn * (1 + TAX_RATE)

final_prices = map(get_price_with_tax, txns)

print(list(final_prices))

Simple one line code.

squares = [i * i
   for i in range(10)
]
print(squares)

Suggestion : 2

Last Updated : 14 Sep, 2021,GATE CS 2021 Syllabus

List of Tuples[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]

Suggestion : 3

Don't make dynamically named variables. It makes it hard to program with them. Instead, use a dict:

x = [100, 2, 300, 4, 75]
dct = {}
for i in x:
   dct['lst_%s' % i] = []

print(dct)
# {
   'lst_300': [],
   'lst_75': [],
   'lst_100': [],
   'lst_2': [],
   'lst_4': []
}

Use a dictionary to hold your lists:

In[8]: x = [100, 2, 300, 4, 75]

In[9]: {
   i: []
   for i in x
}
Out[9]: {
   2: [],
   4: [],
   75: [],
   100: [],
   300: []
}

To access each list:

In[10]: d = {
   i: []
   for i in x
}

In[11]: d[75]
Out[11]: []

And if you really want to have lst_ in each label:

In[13]: {
   'lst_{}'.format(i): []
   for i in x
}
Out[13]: {
   'lst_100': [],
   'lst_2': [],
   'lst_300': [],
   'lst_4': [],
   'lst_75': []
}

In this case the chosen type is a list, which will give you empty lists in the dictionary:

>>> from collections
import defaultdict
   >>>
   d = defaultdict(list) >>>
   d[100]
   []

Suggestion : 4

last modified July 29, 2022

1._
#!/usr/bin/python

words = ["cup", "star", "falcon", "cloud", "wood", "door"]

for word in words:

   print(word)

The example goes over the elements of a list of words with the for statement.

$. / list_loop_for.py
cup
star
falcon
cloud
wood
door
3._
#!/usr/bin/python

words = ["cup", "star", "falcon", "cloud", "wood", "door"]

for word in words:

   print(word)
else:

   print("Finished looping")
5._
#!/usr/bin/python

words = ["cup", "star", "falcon", "cloud", "wood", "door"]

for idx, word in enumerate(words):

   print(f "{idx}: {word}")

With the help of the enumerate function, we print the element of the list with its index.

$. / list_loop_enumerate.py
0: cup
1: star
2: falcon
3: cloud
4: wood
5: door

Suggestion : 5

Software Development Forum , I was wondering if there is any way to created a series of lists in a for-loop so that the first list created is named NAME0 or name_0 or indexed in some way. What I have right now is, We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge. , Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

I was wondering if there is any way to created a series of lists in a for-loop so that the first list created is named NAME0 or name_0 or indexed in some way. What I have right now is

for j in range(int(L)):
   popsizelocus_j = []
# this works, but see below
# allTheLists = []
#
for j in range(int(L)):
   # allTheLists[j] = []
# more pythonic:
   allTheLists = [
      []
      for x in range(int(L))
   ]
#...

   allTheLists[j].append(jListItem)
printAllTheLiats[listIndex][itemIndex]
# etc
# this works, but see below
# allTheLists = []
#
for j in range(int(L)):
   # allTheLists[j] = []
# more pythonic:
   allTheLists = [
      []
      for x in range(int(L))
   ]
#...

   allTheLists[j].append(jListItem)
printAllTheLiats[listIndex][itemIndex]
# etc
mainlist = []

for i in range(10):
   a = 'name_'
b = str(i)
c = a + b
c = [i]
mainlist.append((a + b) + '_st00f')

print(mainlist)

It is very difficult or error prone to do assignment to list elements so often I prefer to use dicts.

# elements of list are mutable and can be variable reference, not values
L = '10'
allthelists = [
   []
   for x in range(int(L))
]
#...
   j = 5
newitem = ['abc']
allthelists[j] = newitem # # wrong, or more dangerous
# #allthelists[j] = newitem[: ] # # right, or safer, copy by[: ], newitem does not change

moreitem = 'def'

allthelists[j].append(moreitem) # # changes newitem
if not copy

print 'New item', newitem

newitem = 'ghi'
# # in this
case no problem as newitem overwriten

print "allthelists:"
print allthelists # # element of allthelist did not change