Python Forum
Append list into list within a for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Append list into list within a for loop
#3
list.append(item) does not return a list. The reason for this is append modifies the list instead of creating a new list.

Your function should return a list but it doesn't. You throw the list away as soon as the function exits. You try to get the list by using a variable that has the same name (seznam) as a local variable in the function, but will not work. This doesn't matter much because you never call your triangle function anyway.

You are writing this program in Python, so use Python loops, not C loops.
five_a = []
for a in 'aaaaa':
     five_a .append(a)
# or
for _ in range(5):
    five_a .append('a')
There are shorter ways than using a loop to initialize a list. You can use a list comprehension:
five_a  = ['a' for _ in range(5)])
Or you can use an initializer.
five_a = (['a']*(5))
To get a list of lists you could have a loop inside of a loop, or you could put an list comprehension or an initialize inside a loop. You could also use a list comprehension that uses a generator to make the inner and outer lists. Or you could use a generator generator inside of a generator. Your triangle generator program can be written in a single line of Python code.
Reply


Messages In This Thread
Append list into list within a for loop - by rama27 - Jul-20-2020, 09:56 PM
RE: Append list into list within a for loop - by deanhystad - Jul-21-2020, 04:49 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 456 Mar-14-2024, 06:26 PM
Last Post: flash77
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,155 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,510 May-01-2023, 09:06 PM
Last Post: deanhystad
Question How to append integers from file to list? Milan 8 1,443 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  List all possibilities of a nested-list by flattened lists sparkt 1 912 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Big O runtime nested for loop and append yarinsh 4 1,369 Dec-31-2022, 11:50 PM
Last Post: stevendaprano
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,828 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  convert this List Comprehensions to loop jacklee26 8 1,500 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  read a text file, find all integers, append to list oldtrafford 12 3,508 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
Question Keyword to build list from list of objects? pfdjhfuys 3 1,555 Aug-06-2022, 11:39 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020