Home > Mobile >  Lists and indices in Python
Lists and indices in Python

Time:10-12

I have a list:

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]

I can access each food item by their positions and print something, like this:

"You do have food, your options are {} or {} or {} or {}".format(
    food_list[0], food_list[1],  food_list[3], food_list[4]
)

(without including the last item: 'cooking oil')

However, if the length of the list is altered in any way, this will give an index (out of range) error.

How do I get items in the list, put them within a sentence as above without getting any errors if the list length is altered?

CodePudding user response:

You can do this in one line. for e.g.

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
"You do have food, your options are {}".format(" or ".join(food_list[:-1]))

Output:

You do have food, your options are chicken or mixed veggies or greens or beans or corn

ps: this will also exclude the last food item in the list.

CodePudding user response:

Try using:

options = " or ".join(food_list)

CodePudding user response:

Here, you want to use something like a simple for-loop:

string = "You do have food, your options are "
for food in food_list:
   string  = food   " or "
string = string[:-3]
print(string)

Here, you remove the last few characters to remove the last "or", while dynamically adding each item in the list.

CodePudding user response:

TL;DR

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
"You do have food, your options are {}".format(" or ".join(food_list))

There would be plenty of ways to do what you're asking for.

join

join, joins a containers each element into a string:

",".join(["mohammad", "Shameoni", "Niaei"])
#'mohammad,Shameoni,Niaei'

loops

You can easily loop through the iterable and append them into a string.

my_string = ""
for element in ["mohammad", "Shameoni", "Niaei"]:
    my_string  = element   ","

my_string = my_string[:-1]
#'mohammad,Shameoni,Niaei'

Use one of above.

CodePudding user response:

Try using fstring.

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
print(f"You do have food, your options are {food_list[0]} or {food_list[1]} or {food_list[3]} or {food_list[4]}")
  • Related