Home > Back-end >  Append a list where name of new item is conditional on its position in the list
Append a list where name of new item is conditional on its position in the list

Time:01-31

I'm trying to append an item to a list where the name of the item is conditional on its index in the list but so far to no avail.

Here is my code so far:

y = [y1, y2, y3]
next_y = input("Would you like to create another y? ")
if input == 'yes':
     y.append(len(y)   1, 'y%i')

Attempt 2:

y = [y1, y2, y3]
create_y = input('would you like to create a y? ')
if input == 'yes':
    next_y = len(y)   1
    if next_y > len(y):
        y.append('y'  next_y)

print(y)

Neither of these or many other attempts has succeeded.

CodePudding user response:

Is this what you want,

y = ['y1', 'y2', 'y3']
create_y = input(": ")
if create_y.lower() == "yes":
    y.append(f"y{len(y)   1}")

print(y) #Output = ['y1', 'y2', 'y3', 'y4']

Here's a good source to learn Python in case you need it https://www.w3schools.com/python/.

CodePudding user response:

Create a class that can pull the next value from a hidden generator.

from itertools import count


class YList:
    def __init__(self, n=0):
        self._ys = (f'y{i}' for i in count(1))
        self.data = [next(self._ys) for _ in range(n)]

    def addnext(self):
        self.data.append(next(self._ys))


y = YList(3)
next_y = input("Would you like to create another y? ")
if next_y == 'yes':
    y.addnext()

Depending on your use case, you may want to provide additional methods for accessing the contents of y.data, or just use y.data directly.

CodePudding user response:

list = ["y1", "y2", "y3"]
create_y = input('would you like to create a y? ')
if create_y == 'yes':
    new_end_number = len(list)   1
    list.append(('y'  str(new_end_number)))
print(list)

CodePudding user response:

This code should work:

y = ['y1', 'y2', 'y3']
next_y = input("Would you like to create another y? ")
if next_y == 'yes':
     len = len(y)   1
     y.append('y'   str(len))
     print(y)
  •  Tags:  
  • Related