Home > Back-end >  Python for loop to fetch only the first x number of elements
Python for loop to fetch only the first x number of elements

Time:12-05

I'm new to programming so bear with me :), I am trying to create a for loop to only show the first few elements of a 2d list. there will be 2 lists 1 that shows the first elements up to a hidden password wherein the user will be asked if they wish to see the full row with the unhidden password. I can't seem to get them for loop to only print the first 0 - 5 elements of each row. The code linked below is perfect for the 2nd loop but I need help to create a for loop that prints from [0:5] for example.

allUserDetails = [["John", "Doe", "User", "Sales", "johndoe91", "Hidden", "Viewable"],
                  ["James", "Hill", "Admin", "Administrator", "hill95", "Hidden", "Viewable"]]

showRecords = 0

            for row in range(len(allUserDetails)): # loop prints the full list
                showRecords  = 1
                print("-" * 25)
                print("Record: ", showRecords)
                for col in range(len(allUserDetails[row])):
                    print(allUserDetails[row][0:][col][0:])
            showRecords = 0
            print("-" * 25)
            print()

Any help would be greatly appreciated :)

CodePudding user response:

From what i understood, you want to only print the first five elements of each row?

In that case, you can iterate over the list to get the rows, and then slice the rows. An implementation of this could look something like this:

for row in allUserDetails:
for element in row[0:5]: # the rows have been sliced to only show element 0 - 5
    print(element)
print("-" * 25)

CodePudding user response:

I would suggest using another for loop inside the row loop, which will help pick out n elements from the row

for row in allUserDetails: #Loops through all arrays in the 2D array
    for i in range(5): #Loops through the first five elements of the row
        print(row[i])

for row in allUserDetails will set the variable row to an array of Strings as defined in your 2D array.

for i in range(n) will loop through that row n times, and then you can print out every string found in there using print(row[i])

  • Related