Zoe  Gutmann

Zoe Gutmann

1671330180

Keyboard Accessibility in JavaScript

In this JavaScript article, we will learn about Keyboard Accessibility in JavaScript. For keyboard accessibility purposes, most of the job is done with basic tools that open many possibilities for keyboard interactivity. This article covers a toolset that you can mix into different components to improve accessibility for keyboard users.

The Basics #

Most of the time, your job with JavaScript to enhance components’ keyboard accessibility will be done with just a handful of tools, including the use of event listeners and certain JavaScript methods of a couple of Web APIs that can help us in this task.

One of the most important tools we have to add interactivity to our projects is the existence of events, which is the execution of functions that trigger when the element you’re checking receives a change.

keydown EVENT #

One example of an event you can listen to with this Web API is the keydown event, which checks when a key is pressed.

Now, this isn’t used to add keyboard accessibility to elements like buttons or links because, by default, when you add a click event listener to them, this will also trigger the event when you use the Enter (for button and links) and Space keys (button only). Instead, the utility of the keydown event comes when you need to add functionality to other keys.

To add an example, let’s come back to the tooltip we created in the first part of this article. I mentioned that this tooltip needs to be closed when you press the Esc key. We’d need a keydown event listener to check if the pressed key is Esc. For that, we need to detect the event’s pressed key. In this case, we’ll check the event key’s property.

We’ll use keycode.info to check the event dump for this key. If you press the Esc key on this page, you’ll notice that e.key is equal to "Escape".

Note: There are two other ways to detect the pressed key, and those are checking e.keyCode and e.which. They will return a number. In the case of the Esc key, it’ll be 27. But, keep in mind those are deprecated alternatives, and while they work, e.key is the preferred option.

With that, we need to select our buttons and add the event listener. My approach to this matter is to use this event listener to add a class to the button and add this class as an exception to show it using the :not() pseudo-class. Let’s start changing our CSS a bit:

button:not(.hide-tooltip):hover + [role="tooltip"],
button:not(.hide-tooltip):focus + [role="tooltip"],
[role="tooltip"]:hover {
  display: block;
}

Now, with this exception added, let’s create our event listener!

const buttons = [...document.querySelectorAll("button")]

buttons.forEach(element => {
  element.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      element.classList.add("hide-tooltip")
    }
  })
})

And there you have it! With just a sprinkle of JavaScript, we have added an accessibility function to our tooltip. And that was just the start of what we can do with a keydown event listener. It’ll be a crucial tool to improve keyboard accessibility for multiple components, but there is another event listener we should take into consideration.

blur EVENT #

There is another event we’ll use often. This one detects when the element stops receiving focus. This event listener is important, and most of the time, you’ll use it to reverse the possible changes you have made with the keydown event listener.

Let’s come back to the tooltip. Right now, it has a problem: if you press the Esc key to close the tooltip, and then you focus on the same element again, the tooltip won’t appear. Why? Because we added the hide-tooltip class when you press the Esc key, but we never removed this class. This is where blur comes into play. Let’s add an event listener to revert this functionality.

element.addEventListener("blur", (e) => {
  if (element.classList.contains("hide-tooltip")) {
    element.classList.remove("hide-tooltip");
  }
});

OTHER EVENT LISTENERS (AND WHY YOU MIGHT DON’T NEED THEM) #

I mentioned that we’re going to need two event listeners in our toolkit, but there are other event listeners you could use, like focusout or focus. However, I think use cases for them are quite scarce. There is a special mention to focus because even if you can find good use cases for it, you need to be very careful. After all, if you don’t use it properly, you can cause a change of context.

A change of context is defined by WCAG as “major changes that, if made without user awareness, can disorient users who are not able to view the entire page simultaneously.” Some examples of change of context include:

  • Opening a new window;
  • Changing the layout of your site significantly;
  • Moving the focus to another part of the site.

This is important to keep in mind because creating a change of context at the moment of focusing on an element is a failure of WCAG criteria 3.2.1:

When any user interface component receives focus, it does not initiate a change of context.

— Success Criterion 3.2.1: Focus order

If you’re not careful, bad use of a function that listens to the focus event can create a change of context. Does that mean you shouldn’t use it? Not really, but to be honest, I can hardly find a use for this event. Most of the time, you’ll be using the :focus pseudo-class to create similar functionalities.

With that said, there is at least one component pattern that can benefit from this event listener in some cases, but I’ll cover it later when I start talking about components, so let’s put a pin on that topic for now.

focus() METHOD #

Now, this is something we’ll be using with some frequency! This method from the HTMLElement API allows us to bring the keyboard focus to a particular element. By default, it’ll draw the focus indicator in the element and will scroll the page to the element’s location. This behavior can be changed with a couple of parameters:

  • preventScroll
    When it’s set to true, will make the browser doesn’t scroll until the programmatically focused element.
  • focusVisible
    When set to false, it will make the programmatically focused element doesn’t display its focus indicator. This property works only on Firefox right now.

Keep in mind that to focus the element, it needs to be either focusable or tabbable. If you need to bring the focus to a normally not tabbable element (like a dialog window), you’ll need to add the attribute tabindex with a negative integer to make it focusable. You can check out how tabindex works in the first part of this guide.

<button id="openModal">Bring focus</button>
<div id="modal" role="dialog" tabindex="-1">
  <h2>Modal content</h2>
</div>

Then we’ll add a click event listener to the button to make the dialog window focused:

const button = document.querySelector("#openModal");
const modal = document.querySelector("#modal")

button.addEventListener("click", () => {
  modal.focus()
})

And there you have it! This method will be very handy in a lot of components in tandem with the keydown attribute, so understanding how both of them work is crucial.

CHANGING HTML ATTRIBUTES WITH JAVASCRIPT #

Certain HTML attributes need to be modified with JavaScript to create accessibility in complex component patterns. Two of the most important ones for keyboard accessibility are tabindex and the more recently added inert. tabindex can be modified using setAttribute. This attribute requires two parameters:

  • name
    It checks the name of the attribute you want to modify.
  • value
    It will add the string this attribute requires if it doesn’t require a particular attribute (for example, if you add the attributes hidden or contenteditable, you’ll need to use an empty string).

Let’s check a quick example of how to use it:

const button = document.querySelector("button")

button.setAttribute("tabindex", "-1")

setAttribute will help a lot for accessibility in general. (I use it a lot to change ARIA attributes when needed!) But, when we talk about keyboard accessibility, tabindex is almost the only attribute you’ll be modifying with this method.

I mentioned the inert attribute before, and this one works a bit differently because it has its own property in the HTMLElement Web API. HTMLElement.inert is a boolean value that will let us toggle the inert attribute.

Keep in mind a couple of things before thinking about using this attribute:

  • You’ll need a polyfill because it’s not fully implemented in all browsers and is still quite recent. This polyfill created by Chrome engineers works pretty well in the tests I have made, so if you need this property, this is a safe approach, but keep in mind that it might have unexpected behaviors.
  • You can use setAttribute to change this attribute as well! Both work equally well, even with a polyfill. Whichever you decide to use is up to you.
const button = document.querySelector("button")

// Syntax with HTMLElement.inert
button.inert = true

// Syntax with Element.setAttribute()
button.setAttribute("inert", "")

This combination of tools will be handy for keyboard accessibility purposes. Now let’s start to see them in action!

Component Patterns #

TOGGLETIPS #

A button being keyboard focused with a message below it that says 'Custom content here'

Carbon Design System toggletip. (Large preview)

We learned how to make a tooltip in the previous part, and I mentioned how to enhance it with JavaScript, but there is another pattern for this kind of component called toggletip, which is a tooltip that works when you click them, instead of hovering on them.

Let’s check a quick list of what we need to make sure it happens:

  • When you press the button, the information should be announced to screen readers. That should happen when you press the button again. Pressing the button won’t close the toggletip.
  • The toggletip will be closed when you either click outside the toggletip, stop focusing the button, or press the Esc key.

I’ll take Heydon Pickering’s approach that he talks about in his book Inclusive Components. So, let’s start with the markup:

<p>If you need to check more information, check here
  <span class="toggletip-container">
    <button class="toggletip-button">
      <span class="toggletip-icon" aria-hidden="true">?</span>
      <div class="sr-only">Más información</div>
    </button>
    <span role="status" class="toggletip-info"></span>
  </span>
</p>

The idea is to inject the necessary HTML inside the element with the role="status". That’ll make screen readers announce the content when you click it. We’re using a button element to make it tabbable. Now, let’s create the script to show the content!

toggletipButton.addEventListener("click", () => {
  toggletipInfo.innerHTML = "";
  setTimeout(() => {
    toggletipInfo.innerHTML = toggletipContent;
  }, 100);
});

As Heydon mentions in his book, we use this approach of first removing the container’s HTML content and then using setTimeout to add it to make sure every time you click it, it’ll be announced for screen reader users. Now we need to check that when you’re clicking elsewhere, the content stops showing.

document.addEventListener("click", (e) => {
  if (toggletipContainer !== e.target) {
    toggletipInfo.innerHTML = ""
  }
})

With that out of the way, it’s time to add keyboard accessibility to this component. We don’t need to make the toggletip’s content show when you press the button because a good HTML semantic does that for us already. We need to make the toggletip’s content stop showing when you press the Esc key and when you stop focusing on this button. It works very similarly to what we did for tooltips in the previous section as examples, so let’s start working with that. First, we’ll use the keydown event listener to check when the Esc key is pressed:

toggletipContainer.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    toggletipInfo.innerHTML = ""
    }
})

And now, we need to check the blur event to do the same. This one should be on the button element instead of the container itself.


toggletipButton.addEventListener("blur", () => {
  toggletipInfo.innerHTML = "";
});

And this is our result!

<p>If you need to check more information, check here
  <span class="toggletip-container">
    <button class="toggletip-button">
      <span class="toggletip-icon" aria-hidden="true">?</span>
      <div class="sr-only">Más información</div>
    </button>
    <span role="status" class="toggletip-info"></span>
  </span>
</p>
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

button {
  font-family: inherit;
}

.toggletip-container {
  position: relative;
}

.toggletip-button {
  display: inline-grid;
  place-items: center;
  aspect-ratio: 1;
  border-radius: 50%;
  background-color: rebeccapurple;
  color: white;
  border-color: transparent;
}

.toggletip-button:focus {
  outline: max(2px, 0.08em) solid rebeccapurple;
  outline-offset: max(2px, 0.08em)
}

.toggletip-icon {
  font-family: ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono",
    "Roboto Mono", "Oxygen Mono", "Ubuntu Monospace", "Source Code Pro",
    "Fira Mono", "Droid Sans Mono", "Courier New", monospace;
  font-weight: bold;
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  border: 0;
}

.toggletip-info {
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 30ch;
  padding: 0.5rem;
  border-radius: 10px;
  color: white;
  background-color: black;
  transform: translate(-50%, 100%);
}

.toggletip-info:empty {
  display: none;
}
const toggletipContainer = document.querySelector(".toggletip-container");
const toggletipButton = document.querySelector(".toggletip-button");
const toggletipInfo = document.querySelector(".toggletip-info");
const toggletipContent = `<p>This is the help information about this section.</p>`;

toggletipButton.addEventListener("click", () => {
  toggletipInfo.innerHTML = "";
  setTimeout(() => {
    toggletipInfo.innerHTML = toggletipContent;
  }, 100);
});

document.addEventListener("click", (e) => {
  if (toggletipContainer !== e.target) {
    toggletipInfo.innerHTML = "";
  }
});

toggletipContainer.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    toggletipInfo.innerHTML = "";
  }
});

toggletipButton.addEventListener("blur", () => {
  toggletipInfo.innerHTML = "";
});

As I mentioned, this works very similarly to the tooltip we made, but I did that for a reason. Unless you’re making something very unconventional, those patterns will repeat themselves quite often.

As Stephanie Eckles mentions in her article “4 Required Tests Before Shipping New Features”, there are some expected behaviors keyboard users expect from components, like being able to close something you just opened by pressing the Esc key, or being able to navigate a group of related options using the Arrow keys.

If you keep those patterns in mind, you’ll notice overlap in certain components’ behaviors, and that’ll repeat when you start creating JavaScript code to ensure keyboard accessibility. So keeping this list in mind will help you to understand what requirements the components you’re creating will need.

Speaking of which, let’s check another common component pattern.

TABS #

Two groups of tabs: the first one has grey text and a border at the bottom, and the selected one has darker text with a blue border. The second tab group has grey text and a grey background, while the selected tab has a lighter background and a blue top border

Carbon Design System tabs. (Large preview)

Roving tabindex #

Tabbed interfaces are patterns that you can still see from time to time. They have a very interesting functionality when we talk about keyboard navigation: when you press the Tab key, it’ll go to the active tab panel. To navigate between the tab list, you’ll need to use the Arrow keys. This is a technique called roving tabindex that consists in removing the ability of the non-active elements to be tababble by adding the attribute tabindex="-1" and then using other keys to allow the navigation between those items.

With tabs, this is the expected behavior for those:

  • When you press Left or Up keys, it’ll move the keyboard focus onto the previous tab. If the focus is on the first tab, it’ll move the focus to the last tab.
  • When you press the Right or Down keys, it’ll move the keyboard focus onto the next tab. If the focus is on the first tab, it’ll move the focus to the last tab.

Creating this functionality is a mix of three techniques we saw before: modifying tabindex with setAttribute, the keydown event listener, and the focus() method. Let’s start by checking the markup of this component:

<ul role="tablist">
  <li role="presentation">
    <button id="tab1" role="tab" aria-selected="true">Tomato</button>
  </li>
  <li role="presentation">
    <button id="tab2" role="tab" tabindex="-1">Onion</button>
  </li>
  <li role="presentation">
    <button id="tab3" role="tab" tabindex="-1">Celery</button>
  </li>
  <li role="presentation">
    <button id="tab4" role="tab" tabindex="-1">Carrot</button>
  </li>
</ul>
<div class="tablist-container">
  <section role="tabpanel" aria-labelledby="tab1" tabindex="0">
  </section>
  <section role="tabpanel" aria-labelledby="tab2" tabindex="0" hidden>
  </section>
  <section role="tabpanel" aria-labelledby="tab3" tabindex="0" hidden>
  </section>
  <section role="tabpanel" aria-labelledby="tab4" tabindex="0" hidden>
  </section>
</div>

We are using aria-selected="true" to show which is the active tab, and we’re adding tabindex="-1" to make the non-active tabs unable to be selected with the Tab key. Tabpanels should be tabbable if there is no tabbable element inside of it, so this is why I added the attribute tabindex="0" and the non-active tabpanels are hidden by using the attribute hidden.

Time to add the navigation with the arrow keys. For this, we’ll need to create an array with the tabs and then create a function for it. Our next step is to check which is the first and last tab in the list. This is important because the action that will happen when you press a key will change if the keyboard focus is on one of those elements.

const TABS = [...TABLIST.querySelectorAll("[role='tab']")];

const createKeyboardNavigation = () => {
  const firstTab = TABS[0];
  const lastTab = TABS[TABS.length - 1];
}

After that, we’ll add a keydown event listener to each tab. I’ll start by adding the functionality with Left and Up arrows.

// Previous code of the createKeyboardNavigation function
TABS.forEach((element) => {
  element.addEventListener("keydown", function (e) {
    if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
      e.preventDefault();
      if (element === firstTab) {
        lastTab.focus();
      } else {
        const focusableElement = TABS.indexOf(element) - 1;
        TABS[focusableElement].focus();
      }
    }
  }
}

This is what’s happening here:

  • First, we check that the pressed key is the Up or Left arrow. For that, we check the event.key.
  • If that’s true, we need to prevent those keys scroll the page because, remember, by default, they do that. We can use e.preventDefault() for this goal.
  • If the focused key is the first tab, it’ll automatically bring the keyboard focus to the last one. This is made by calling the method focus() to focus the last tab (which we store in a variable).
  • If it’s not the case, we need to check which is the position of the active tab. As we store the tab elements in an array, we can use the method indexOf() to check the position.
  • As we’re trying to navigate to the previous tab, we can subtract 1 from the result of indexOf() and then search the corresponding element in the TABS array and programmatically focus it with the focus() method.

Now we need to do a very similar process with the Down and Right keys:

// Previous code of the createKeyboardNavigation function
else if (e.key === "ArrowDown" || e.key === "ArrowRight") {
  e.preventDefault();
  if (element == lastTab) {
    firstTab.focus();
  } else {
    const focusableElement = TABS.indexOf(element) + 1;
    TABS[focusableElement].focus();
  }
}

As I mentioned, it’s a very similar process. Instead of subtracting one from the indexOf() result, we add 1 because we want to bring the keyboard focus to the next element.

Showing The Content And Changing HTML Attributes #

We created the navigation, and now we need to show and hide the content as well as manipulate the attributes aria-selected and tabindex. Remember, we need to make that when the keyboard focus is on the active panel, and you press Shift + Tab, the focus should be in the active tab.

First, let’s create the function that shows the panel.

const showActivePanel = (element) => {
  const selectedId = element.target.id;
  TABPANELS.forEach((e) => {
    e.hidden = "true";
  });
  const activePanel = document.querySelector(
    `[aria-labelledby="${selectedId}"]`
  );
  activePanel.removeAttribute("hidden");
};
<

What we’re doing here is checking the id of the tab is being pressed, then hiding all the tab panels, and then looking for the tab panel we want to activate. We’ll know it’s the tab because it has the attribute aria-labelledby and uses the same value as the tab’s id. Then we show it by removing the attribute hidden.

Now we need to create a function to change the attributes:

const handleSelectedTab = (element) => {
  const selectedId = element.target.id;
  TABS.forEach((e) => {
    const id = e.getAttribute("id");
    if (id === selectedId) {
      e.removeAttribute("tabindex", "0");
      e.setAttribute("aria-selected", "true");
    } else {
      e.setAttribute("tabindex", "-1");
      e.setAttribute("aria-selected", "false");
    }
  });
};

What we’re doing here is, again, checking the id attribute and then looking at each tab. We’ll check if this tab’s id corresponds with the pressed element’s id.

If it’s the case, we’ll make it keyboard tabbable by either removing the attribute tabindex (because it’s a button, so it’s keyboard tabbable by default) or by adding the attribute tabindex="0". Additionally, we’ll add an indicator to screen reader users that this is the active tab by adding the attribute aria-selected="true".

If it doesn’t correspond, tabindex and aria-selected will be set to -1 and false, respectively.

Now, all we need to do is add a click event listener to each tab to handle both functions.

TABS.forEach((element) => {
  element.addEventListener("click", (element) => {
    showActivePanel(element),
    handleSelectedTab(element);
  });
});

And that’s it! We created the functionality to make tabs work, but we can do a little something else if needed.

Activate Tab On Focus #

Do you remember what I mentioned about the focus event listener? You should be careful when you use it because it can create a change of context by accident, but it has some use, and this component is a perfect opportunity to use it!

According to ARIA Authoring Practices Guide (APG), we can make the displayed content show when you focus on the tab. This concept is often referred to as a follow focus and can be helpful for keyboard and screen reader users because it allows navigating more easily through the content.

However, you need to keep a couple of considerations about it:

  • If showing the content means making a lot of petitions and, by extension, making the network slower, making the displayed content follow the focus is not desired.
  • If it changes the layout in a significant way, that can be considered a change of context. That depends on the kind of content you want to show, and doing a change of context on focus is an accessibility issue, as I explained previously.

In this case, the amount of content doesn’t suppose a big change in either network or layout, so I’ll make the displayed content follows the focus of the tabs. This is a very simple task with the focus event listener. We can just literally copy and paste the event listener we created and just change click to focus.

TABS.forEach((element) => {
  element.addEventListener("click", (element) => {
    showActivePanel(element),
    handleSelectedTab(element);
  });

  element.addEventListener("focus", (element) => {
    showActivePanel(element),
    handleSelectedTab(element);
  });
});

And there you have it! Now the displayed content will work without the need to click the tab. Doing that or making it only work with a click is up to you and is surprisingly a very nuanced question. Personally, I’d stick just with making it shows when you press the tab because I think the experience of changing the attribute aria-selected by just focusing on the element can be slightly confusing. Still, it’s just a hypothesis on my part so take what I say with a grain of salt and always check it with users.

Additional keydown Event Listeners #

Let’s come back to the createKeyboardNavigation for a moment. There are a couple of keys we can add. We can make the Home and End key brings the keyboard focus to the first and last tab, respectively. This is completely optional, so it’s ok if you don’t do it, but just to reiterate how a keydown event listener helps out, I’ll do that.

It’s a very easy task. We can create another couple of if statements to check if the Home and End keys are being pressed, and because we have stored the first and last tabs in variables, we can you focus them with the focus() method.

// Previous code of the createKeyboardNavigation function
else if (e.key === "Home") {
  e.preventDefault();
  firstTab.focus()
} else if (e.key === "End") {
  e.preventDefault();
  lastTab.focus()
}

And this is our result!

<ul role="tablist">
  <li role="presentation">
    <button id="tab1" role="tab" aria-selected="true">Tomato</button>
  </li>
  <li role="presentation">
    <button id="tab2" role="tab" tabindex="-1">Onion</button>
  </li>
  <li role="presentation">
    <button id="tab3" role="tab" tabindex="-1">Celery</button>
  </li>
  <li role="presentation">
    <button id="tab4" role="tab" tabindex="-1">Carrot</button>
  </li>
</ul>
<div class="tablist-container">
  <section role="tabpanel" aria-labelledby="tab1" tabindex="0">
    <img src="https://images.unsplash.com/photo-1607305387299-a3d9611cd469?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80" alt="A red tomato">
  </section>
  <section role="tabpanel" aria-labelledby="tab2" tabindex="0" hidden>
    <img src="https://images.unsplash.com/photo-1587049633312-d628ae50a8ae?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=580&q=80" alt="Two yellow onions">
  </section>
  <section role="tabpanel" aria-labelledby="tab3" tabindex="0" hidden>
    <img src="https://images.unsplash.com/photo-1580391564590-aeca65c5e2d3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80" alt="A celery">
  </section>
  <section role="tabpanel" aria-labelledby="tab4" tabindex="0" hidden>
    <img src="https://images.unsplash.com/photo-1589927986089-35812388d1f4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80" alt="3 carrots on a wooden table">
  </section>
</div>
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

[aria-selected="true"] {
  background-color: tomato;
}

[role="tablist"] {
  list-style: none;
  padding-left: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 1em;
}

[role="tablist"] > * {
  flex-grow: 1;
  flex-basis: calc(( 500px - 100%) * 999);
}

[role="tab"] {
  padding: 0.5em 1em;
  width: 100%;
  font-size: 1.2rem;
  font-family: inherit;
  border-color: black;
}

[role="tab"]:focus-visible {
  outline-offset: -4px;
  outline: 2px solid currentcolor
}

img {
  display: block;
  margin-inline: auto;
  max-width: 100%;
  max-height: 80vh;
}

[role="tabpanel"] {
  padding: 1rem;
}

[role="tabpanel"]:focus-visible {
  background-color: #ffcdbf;
  outline-color: transparent; 
}
const TABLIST = document.querySelector("[role='tablist']");
const TABS = [...TABLIST.querySelectorAll("[role='tab']")];
const TABPANELS = [...document.querySelectorAll("[role='tabpanel']")];

const createKeyboardNavigation = () => {
  const firstTab = TABS[0];
  const lastTab = TABS[TABS.length - 1];

  TABS.forEach((element) => {
    element.addEventListener("keydown", function (e) {
      if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
        e.preventDefault();
        if (element == firstTab) {
          lastTab.focus();
        } else {
          const focusableElement = TABS.indexOf(element) - 1;
          TABS[focusableElement].focus();
        }
      } else if (e.key === "ArrowDown" || e.key === "ArrowRight") {
        e.preventDefault();
        if (element == lastTab) {
          firstTab.focus();
        } else {
          const focusableElement = TABS.indexOf(element) + 1;
          TABS[focusableElement].focus();
        }
      } else if (e.key === "Home") {
        e.preventDefault();
        firstTab.focus()
      } else if (e.key === "End") {
        e.preventDefault();
        lastTab.focus()
      }
    });
  });
};

const showActivePanel = (element) => {
  const selectedId = element.target.id;
  TABPANELS.forEach((e) => {
    e.hidden = "true";
  });
  const activePanel = document.querySelector(
    `[aria-labelledby="${selectedId}"]`
  );
  activePanel.removeAttribute("hidden");
};

const handleSelectedTab = (element) => {
  const selectedId = element.target.id;
  TABS.forEach((e) => {
    const id = e.getAttribute("id");
    if (id === selectedId) {
      e.removeAttribute("tabindex", "0");
      e.setAttribute("aria-selected", "true");
    } else {
      e.setAttribute("tabindex", "-1");
      e.setAttribute("aria-selected", "false");
    }
  });
};

createKeyboardNavigation();

TABS.forEach((element) => {
  element.addEventListener("click", (element) => {
    showActivePanel(element), handleSelectedTab(element);
  });

  element.addEventListener("focus", (element) => {
    showActivePanel(element), handleSelectedTab(element);
  });
});

With this code, we have made this component accessible for keyboard and screen reader users. This shows how useful the basic concepts of keydown event listener, the focus() method, and the changes we can make with setAttribute are to manipulate complex components. Let’s check one more, a very complicated one, and how the inert attribute can help us to handle this task easily.

MODALS #

An opened modal with some filler text and two buttons that say Cancel and Save

Carbon Design System modal. (Large preview)

Opening And Closing The Modal #

Modals are quite a complex pattern when we talk about keyboard accessibility, so let’s start with an easy task — opening and closing the modal.

It is indeed easy, but you need to keep something in mind: it’s very likely the button opens the modal, and the modal is far away in the DOM. So you need to manage the focus programmatically when you manage this component. There is a little catch here: you need to store which element opened the modal so we can return the keyboard focus returns to this element at the moment we close it.

Luckily, there is an easy way to do that, but let’s start by creating the markup of our site:

<body>
  <header>
    <!-- Header's content -->
  </header>
  <main>
    <!-- Main's content -->
    <button id="openModal">Open modal</button>
  </main>
  <footer>
    <!-- Footer's content -->
  </footer>
  <div role="dialog"
    aria-modal="true"
    aria-labelledby="modal-title"
    hidden
    tabindex="-1">
    <div class="dialog__overlay"></div>
    <div class="dialog__content">
      <h2 id="modal-title">Modal content</h2>
      <ul>
        <li><a href="#">Modal link 1</a></li>
        <li><a href="#">Modal link 2</a></li>
        <li><a href="#">Modal link 3</a></li>
      </ul>
      <button id="closeModal">Close modal</button>
    </div>
  </div>
</body>

As I mentioned, the modal and the button are far away from each other in the DOM. This will make it easier to create a focus trap later, but for now, let’s check the modal’s semantics:

  • role="dialog" will give the element the required semantics for screen readers. It needs to have a label to be recognized as a dialog window, so we’ll use the modal’s title as the label using the attribute aria-labelledby.
  • aria-modal="true" helps to make a screen reader user can only read the content of the element’s children, so it blocks access from screen readers. However, as you can see on the aria-modal page for a11ysupport.com, it’s not fully supported, so you can’t rely just on that for this task. It’ll be useful for screen readers who support it, but you’ll see there is another way to ensure screen reader users don’t interact with anything besides the modal once it’s opened.
  • As I mentioned, we need to bring the keyboard focus to our modal, so this is why we added the attribute tabindex="-1".

With that in mind, we need to create the function to open our modal. We need to check which was the element that opened it, and for that, we can use the property document.activeElement to check which element is being keyboard-focused right now and store it in a variable. This is my approach for this task:

let focusedElementBeforeModal

const modal = document.querySelector("[role='dialog']");
const modalOpenButton = document.querySelector("#openModal")
const modalCloseButton = document.querySelector("#closeModal")

const openModal = () => {
  focusedElementBeforeModal = document.activeElement
  
  modal.hidden = false;
  modal.focus();
};

It’s very simple:

  1. We store the button that opened the modal;
  2. Then we show it by removing the attribute hidden;
  3. Then we bring the focus to the modal with the focus() method.

It’s essential that you store the button before bringing the focus to the modal. Otherwise, the element that would be stored in this case would be the modal itself, and you don’t want that.

Now, we need to create the function to close the modal:

const closeModal = () => {
  modal.hidden = true;
  focusedElementBeforeModal.focus()
}

This is why it’s important to store the proper element. When we close the modal, we’ll bring back the keyboard focus to the element that opened it. With those functions created, all we have to do is add the event listeners for those functions! Remember that we also need to make the modal closes when you press the Esc key.

modalOpenButton.addEventListener("click", () => openModal())
modalCloseButton.addEventListener("click", () => closeModal())
modal.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeModal()
  }
})

Right now, it looks very simple. But if that were all, modals wouldn’t be considered a complex pattern for accessibility, were they? This is where we need to create a very key task for this component, and we have two ways to do it.

Creating A Focus Trap #

A focus trap ensures the keyboard focus can’t escape from the component. This is crucial because if a keyboard user can interact with anything outside a modal once it’s opened, it can create a very confusing experience. We have two ways to do that right now.

One of them is checking each element that can be tabbable with a keyboard, then storing which are the first and the last, and doing this:

  • When the user presses Shift + Tab and the keyboard focus is on the first tabbable element (remember, you can check that with document.activeElement), the focus will go to the last tabbable element.
  • When the user presses Tab, and the keyboard focus is on the last tabbable element, the keyboard focus should go to the first tabbable element.

Normally, I’d show you how to make this code, but I think A11y solutions made a very good script to create a focus trap. It sort of works as the keyboard navigation with the arrow keys we created for tab elements (as I mentioned before, patterns repeat themselves!), so I invite you to check this page.

I don’t want to use this approach as the main solution because it’s not exactly flawless. Those are some situations this approach doesn’t cover.

The first one is that it doesn’t take into account screen readers, especially mobile screen readers. As Rahul Kumar mentions in his article “Focus Trapping for Accessibility (A11Y)”, Talkback and Voiceover allow the user of gestures and double taps to navigate to the next or previous focusable element, and those gestures can’t be detected with an event listener because those gestures are something that technically speaking doesn’t happen in the browser. There is a solution for that, but I’ll put a pin on that topic for a moment.

The other concern is that this focus trap approach can lead to weird behaviors if you use certain combinations of tabbable elements. Take, for example, this modal:

A modal with the title 'Survey' and a question that says 'How big is your team?' and three answer options in radio inputs: 1 to 3 people, 4 to 10 people and more than 10 people, Below it, there is a button with the name 'Send answer'

(Large preview)

Technically speaking, the first tabbable element is the first input. However, all the inputs in this example should focus on the last tabbable element (in this case, the button element) when the user presses the keys Shift + Tab. Otherwise, it could cause a weird behavior if the user presses those keys when the keyboard focus is on the second or third input.

If we want to create a more reliable solution, the best approach is using the inert attribute to make outer content inaccessible for screen readers and keyboard users, ensuring they can interact only with the modal’s content. Remember, this will require the inert polyfill to add more robustness to this technique.

Note: It’s important to note that despite the fact a focus trap and using inert in practice help to ensure keyboard accessibility for modals, they don’t work exactly the same. The main difference is that setting all documents but modal as inert, it’ll still let you move outside of the website and interact with the browser’s elements. This is arguably better for security concerns but deciding if you want to create a focus trap manually or use the inert attribute is up to you.

What we’ll do first is select all areas that don’t have the role dialog. As inert will remove all keyboard and screen reader interaction with the elements and their children, we’ll need to select only the direct children of body. This is why we let the modal container exist at the same level as tags like main, header, or footer.

// This selector works well for this specific HTML structure. Adapt according to your project.
const nonModalAreas = document.querySelectorAll("body > *:not([role='dialog'])")

Now we need to come back to the openModal function. After opening the modal, we need to add the attribute inert to those elements. This should be the last step in the function:

const openModal = () => {
  // Previously added code
  nonModalAreas.forEach((element) => {
    element.inert = true
  })
};

What about when you close the modal? You need to go to the closeModal function and remove this attribute. This needs to go before everything else in the code runs. Otherwise, the browser won’t be able to focus on the button that opened this modal.

const closeModal = () => {
  nonModalAreas.forEach((element) => {
    element.inert = false;
  });
// Previously added code
};

And this is our result!

<body>
  <header>
    <!-- Header's content -->
  </header>
  <main>
    <!-- Main's content -->
    <button id="openModal">Do survey</button>
  </main>
  <footer>
    <!-- Footer's content -->
  </footer>
  <div role="dialog" aria-modal="true" aria-labelledby="modal-title" hidden tabindex="-1">
    <div class="dialog__overlay"></div>
    <div class="dialog__content">
      <h2 id="modal-title">Survey</h2>
      <form action="" novalidate>
        <fieldset>
          <legend>How big is your team?</legend>
          <div>
            <input type="radio" id="answer1" name="question1">
            <label for="answer1" name="question1">1 to 3 people</label>
          </div>
          <div>
            <input type="radio" id="answer2" name="question1">
            <label for="answer2">4 to 10 people</label>
          </div>
          <div>
            <input type="radio" id="answer3" name="question1">
            <label for="answer3">More than 10 people</label>
          </div>
        </fieldset>
        <button type="button" id="closeModal">Send answer</button>
      </form>
    </div>
  </div>
</body>
body {
  display: grid;
  place-items: center;
  height: 100vh;
  accent-color: rebeccapurple;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

button {
  font-family: inherit;
  padding: 0.5em 1em;
  font-weight: bold;
  background-color: orchid;
  border-color: transparent;
}

button:focus-visible {
  background-color: rebeccapurple;
  color: whitesmoke;
}

[role="dialog"] {
  position: fixed;
  inset: 0;
}

:is(.dialog__overlay, .dialog__content) {
  position: absolute;
  inset: 0;
}

.dialog__overlay {
  
  background-color: hsla(0deg, 0%, 0%, 0.5)
}

.dialog__content {
  display: grid;
  place-items: center;
  top: 50%;
  left: 50%;
  padding: 1em;
  margin-inline: auto;
  width: 80%;
  max-width: 400px;
  height: max-content;
  max-height: 80vh;
  transform: translate(-50%, -50%);
  background-color: whitesmoke;
  border-radius: 2px;
  overflow-y: auto;
}

:is(form, fieldset) {
  display: grid;
  align-items: center;
  gap: 1em;
}

form {
  justify-items: center;
}

fieldset {
  width: 100%;
    border-radius: 10px;
}

legend {
  background-color: rebeccapurple;
  padding: 0.2em 0.5em;
  color: white;
  font-weight: bold;
}
import wicgInert from "https://cdn.skypack.dev/wicg-inert@3.1.2";
let focusedElementBeforeModal;

const modal = document.querySelector("[role='dialog']");
const modalOpenButton = document.querySelector("#openModal");
const modalCloseButton = document.querySelector("#closeModal");
const overlay = document.querySelector(".dialog__overlay");
const nonModalAreas = document.querySelectorAll(
  "body > *:not([role='dialog'], script)"
);

console.log(nonModalAreas);

const openModal = () => {
  focusedElementBeforeModal = document.activeElement;

  modal.hidden = false;
  modal.focus();
  nonModalAreas.forEach((element) => {
    element.inert = true;
  });
};

const closeModal = () => {
  nonModalAreas.forEach((element) => {
    element.inert = false;
  });
  modal.hidden = true;
  focusedElementBeforeModal.focus();
};

modalOpenButton.addEventListener("click", () => openModal());
modalCloseButton.addEventListener("click", () => closeModal());
overlay.addEventListener("click", () => closeModal());
modal.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeModal();
  }
});

Let’s suppose you don’t feel comfortable using the inert attribute right now and want to create a focus trap manually, as the one A11y Solutions shows. What can you do to ensure screen reader users can’t get out of the modal? aria-modal can help with that, but remember, the support for this property is quite shaky, especially for Talkback and VoiceOver for iOS. So the next best thing we can do is add the attribute aria-hidden="true" to all elements that are not the modal. It’s a very similar process to the one we made for the inert attribute, and you can use the same elements in the array we used for this topic as well!

const openModal = () => {
  //Previously added code
  nonModalAreas.forEach((element) => {
    element.setAttribute("aria-hidden", "true")
  });
};

const closeModal = () => {
  nonModalAreas.forEach((element) => {
    element.removeAttribute("aria-hidden")
  });
  // Previously added code
};

So, whether you decide to use the inert attribute or create a focus trap manually, you can ensure user experience for keyboard and screen reader users works at its best.

<dialog> Element #

You might notice the markup I used and that I didn’t use the relatively new <dialog> element, and there is a reason for that. Yes, this element helps a lot by managing focus to the modal and to the button that opened easily, but, as Scott O’Hara points out in his article “Having an open dialog”, it still has some accessibility issues that even with a polyfill are not fully solved yet. So I decided to use a more robust approach there with the markup.

If you haven’t heard about this element, it has a couple of functions to open and close the dialog, as well as some new functionalities that will be handy when we create modals. If you want to check how it works, you can check Kevin Powell’s video about this element.

That doesn’t mean you shouldn’t use it at all. Accessibility’s situation about this element is improving, but keep in mind you still need to take into consideration certain details to make sure it works properly.

OTHER COMPONENT PATTERNS #

I could go on with many component patterns, but to be honest, I think it’ll start getting redundant because, as a matter of fact, those patterns are quite similar between the different kinds of components you can make. Unless you have to make something very unconventional, those patterns we have seen here should be enough!

With that said, how can you know what requirements you will need for a component? This is an answer with many nuances that this article cannot cover. There are some resources like Scott O’Hara’s accessible components’ repository or UK government’s design system, but this is a question that does not have a simple answer. The most important thing about this topic is to always test them with disabled users to know what flaws they can have in terms of accessibility.

Wrapping Up #

Keyboard accessibility can be quite hard, but it’s something you can achieve once you understand how keyboard users interact with a site and what principles you should keep in mind. Most of the time, HTML and CSS will do a great job of ensuring keyboard accessibility, but sometimes you’ll need JavaScript for more complex patterns.

It’s quite impressive what you can do for keyboard accessibility once you notice most of the time, the job is made with the same basic tools. Once you understand what you need to do, you can mix those tools to create a great user experience for keyboard users!

Original article sourced at: https://www.smashingmagazine.com

#javascript 

What is GEEK

Buddha Community

Keyboard Accessibility in JavaScript
Thierry  Perret

Thierry Perret

1662365538

Les Structures De Données Les Plus Couramment Utilisées En Python

Dans tout langage de programmation, nous devons traiter des données. Maintenant, l'une des choses les plus fondamentales dont nous avons besoin pour travailler avec les données est de les stocker, de les gérer et d'y accéder efficacement de manière organisée afin qu'elles puissent être utilisées chaque fois que cela est nécessaire pour nos besoins. Les structures de données sont utilisées pour répondre à tous nos besoins.

Que sont les Structures de Données ?

Les structures de données sont les blocs de construction fondamentaux d'un langage de programmation. Il vise à fournir une approche systématique pour répondre à toutes les exigences mentionnées précédemment dans l'article. Les structures de données en Python sont List, Tuple, Dictionary et Set . Ils sont considérés comme des structures de données implicites ou intégrées dans Python . Nous pouvons utiliser ces structures de données et leur appliquer de nombreuses méthodes pour gérer, relier, manipuler et utiliser nos données.

Nous avons également des structures de données personnalisées définies par l'utilisateur, à savoir Stack , Queue , Tree , Linked List et Graph . Ils permettent aux utilisateurs d'avoir un contrôle total sur leurs fonctionnalités et de les utiliser à des fins de programmation avancées. Cependant, nous nous concentrerons sur les structures de données intégrées pour cet article.

Structures de données implicites Python

Structures de données implicites Python

LISTE

Les listes nous aident à stocker nos données de manière séquentielle avec plusieurs types de données. Ils sont comparables aux tableaux à l'exception qu'ils peuvent stocker différents types de données comme des chaînes et des nombres en même temps. Chaque élément ou élément d'une liste a un index attribué. Étant donné que Python utilise l' indexation basée sur 0 , le premier élément a un index de 0 et le comptage continue. Le dernier élément d'une liste commence par -1 qui peut être utilisé pour accéder aux éléments du dernier au premier. Pour créer une liste, nous devons écrire les éléments à l'intérieur des crochets .

L'une des choses les plus importantes à retenir à propos des listes est qu'elles sont Mutable . Cela signifie simplement que nous pouvons modifier un élément dans une liste en y accédant directement dans le cadre de l'instruction d'affectation à l'aide de l'opérateur d'indexation. Nous pouvons également effectuer des opérations sur notre liste pour obtenir la sortie souhaitée. Passons en revue le code pour mieux comprendre les opérations de liste et de liste.

1. Créer une liste

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Production

['p', 'r', 'o', 'b', 'e']

2. Accéder aux éléments de la liste

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Production

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Ajouter de nouveaux éléments à la liste

#adding item to the list
my_list + ['k']

Production

['p', 'r', 'o', 'b', 'e', 'k']

4. Suppression d'éléments

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Production

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Production

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Liste de tri

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Production

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Production

['y', 'r', 'm', 'l', 'k']

6. Trouver la longueur d'une liste

#finding the length of list
 
len(my_list)

Production

5

TUPLE

Les tuples sont très similaires aux listes avec une différence clé qu'un tuple est IMMUTABLE , contrairement à une liste. Une fois que nous avons créé un tuple ou que nous avons un tuple, nous ne sommes pas autorisés à modifier les éléments qu'il contient. Cependant, si nous avons un élément à l'intérieur d'un tuple, qui est une liste elle-même, alors seulement nous pouvons accéder ou changer dans cette liste. Pour créer un tuple, nous devons écrire les éléments entre parenthèses . Comme les listes, nous avons des méthodes similaires qui peuvent être utilisées avec des tuples. Passons en revue quelques extraits de code pour comprendre l'utilisation des tuples.

1. Créer un tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Production

('apple', 'banana', 'guava')

2. Accéder aux éléments d'un Tuple

#accessing first element in tuple
 
my_tuple[1]

Production

'banana'

3. Longueur d'un tuple

#for finding the lenght of tuple
 
len(my_tuple)

Production

3

4. Conversion d'un tuple en liste

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Production

list

5. Inverser un tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Production

('guava', 'banana', 'apple')

6. Trier un tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Production

('apple', 'banana', 'guava')

7. Supprimer des éléments de Tuple

Pour supprimer des éléments du tuple, nous avons d'abord converti le tuple en une liste comme nous l'avons fait dans l'une de nos méthodes ci-dessus (point n ° 4), puis avons suivi le même processus de la liste et avons explicitement supprimé un tuple entier, juste en utilisant le del déclaration .

DICTIONNAIRE

Dictionary est une collection, ce qui signifie simplement qu'il est utilisé pour stocker une valeur avec une clé et extraire la valeur donnée à la clé. Nous pouvons le considérer comme un ensemble de clés : des paires de valeurs et chaque clé d'un dictionnaire est supposée être unique afin que nous puissions accéder aux valeurs correspondantes en conséquence.

Un dictionnaire est indiqué par l'utilisation d' accolades { } contenant les paires clé : valeur. Chacune des paires d'un dictionnaire est séparée par des virgules. Les éléments d'un dictionnaire ne sont pas ordonnés , la séquence n'a pas d'importance pendant que nous y accédons ou que nous les stockons.

Ils sont MUTABLES ce qui signifie que nous pouvons ajouter, supprimer ou mettre à jour des éléments dans un dictionnaire. Voici quelques exemples de code pour mieux comprendre un dictionnaire en python.

Un point important à noter est que nous ne pouvons pas utiliser un objet mutable comme clé dans le dictionnaire. Ainsi, une liste n'est pas autorisée comme clé dans le dictionnaire.

1. Création d'un dictionnaire

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Ici, les entiers sont les clés du dictionnaire et le nom de ville associé aux entiers sont les valeurs du dictionnaire.

2. Accéder aux éléments d'un dictionnaire

#access an item
 
print(my_dict[1])

Production

'Delhi'

3. Longueur d'un dictionnaire

#length of the dictionary
 
len(my_dict)

Production

3

4. Trier un dictionnaire

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Production

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Ajout d'éléments dans le dictionnaire

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Suppression d'éléments du dictionnaire

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

POSITIONNER

Set est un autre type de données en python qui est une collection non ordonnée sans éléments en double. Les cas d'utilisation courants d'un ensemble consistent à supprimer les valeurs en double et à effectuer des tests d'appartenance. Les accolades ou la set()fonction peuvent être utilisées pour créer des ensembles. Une chose à garder à l'esprit est que lors de la création d'un ensemble vide, nous devons utiliser set(), et . Ce dernier crée un dictionnaire vide. not { }

Voici quelques exemples de code pour mieux comprendre les ensembles en python.

1. Créer un ensemble

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Production

{'apple', 'strawberry', 'mango'}

2. Accéder aux éléments d'un ensemble

#to test for an element inside the set
 
"apple" in my_set

Production

True

3. Longueur d'un ensemble

print(len(my_set))

Production

3

4. Trier un ensemble

print(sorted(my_set))

Production

['apple', 'mango', 'strawberry']

5. Ajout d'éléments dans Set

my_set.add("guava")
print(my_set)

Production

{'apple', 'guava', 'mango', 'strawberry'}

6. Suppression d'éléments de Set

my_set.remove("mango")
print(my_set)

Production

{'apple', 'guava', 'strawberry'}

Conclusion

Dans cet article, nous avons passé en revue les structures de données les plus couramment utilisées en python et avons également vu diverses méthodes qui leur sont associées.

Lien : https://www.askpython.com/python/data

#python #datastructures

Dang  Tu

Dang Tu

1662380058

Các Cấu Trúc Dữ Liệu được Sử Dụng Phổ Biến Nhất Trong Python

Trong bất kỳ ngôn ngữ lập trình nào, chúng ta cần xử lý dữ liệu. Bây giờ, một trong những điều cơ bản nhất mà chúng ta cần làm việc với dữ liệu là lưu trữ, quản lý và truy cập nó một cách hiệu quả theo cách có tổ chức để nó có thể được sử dụng bất cứ khi nào được yêu cầu cho các mục đích của chúng ta. Cấu trúc dữ liệu được sử dụng để đáp ứng mọi nhu cầu của chúng tôi.

Cấu trúc dữ liệu là gì?

Cấu trúc dữ liệu là các khối xây dựng cơ bản của một ngôn ngữ lập trình. Nó nhằm mục đích cung cấp một cách tiếp cận có hệ thống để đáp ứng tất cả các yêu cầu được đề cập trước đó trong bài báo. Các cấu trúc dữ liệu trong Python là Danh sách, Tuple, Từ điển và Tập hợp . Chúng được coi là Cấu trúc dữ liệu ngầm định hoặc được tích hợp sẵn trong Python . Chúng tôi có thể sử dụng các cấu trúc dữ liệu này và áp dụng nhiều phương pháp cho chúng để quản lý, liên quan, thao tác và sử dụng dữ liệu của chúng tôi.

Chúng tôi cũng có các Cấu trúc Dữ liệu tùy chỉnh do người dùng xác định cụ thể là Ngăn xếp , Hàng đợi , Cây , Danh sách được Liên kếtĐồ thị . Chúng cho phép người dùng có toàn quyền kiểm soát chức năng của chúng và sử dụng chúng cho các mục đích lập trình nâng cao. Tuy nhiên, chúng tôi sẽ tập trung vào Cấu trúc dữ liệu tích hợp cho bài viết này.

Python cấu trúc dữ liệu ngầm

Python cấu trúc dữ liệu ngầm

DANH SÁCH

Danh sách giúp chúng tôi lưu trữ dữ liệu của mình một cách tuần tự với nhiều kiểu dữ liệu. Chúng có thể so sánh với mảng với ngoại lệ là chúng có thể lưu trữ các kiểu dữ liệu khác nhau như chuỗi và số cùng một lúc. Mỗi mục hoặc phần tử trong danh sách đều có một chỉ mục được chỉ định. Vì Python sử dụng lập chỉ mục dựa trên 0 , phần tử đầu tiên có chỉ mục là 0 và việc đếm vẫn tiếp tục. Phần tử cuối cùng của danh sách bắt đầu bằng -1 có thể được sử dụng để truy cập các phần tử từ cuối cùng đến đầu tiên. Để tạo một danh sách, chúng ta phải viết các mục bên trong dấu ngoặc vuông .

Một trong những điều quan trọng nhất cần nhớ về danh sách là chúng có thể thay đổi . Điều này đơn giản có nghĩa là chúng ta có thể thay đổi một phần tử trong danh sách bằng cách truy cập trực tiếp vào nó như một phần của câu lệnh gán bằng cách sử dụng toán tử lập chỉ mục. Chúng tôi cũng có thể thực hiện các thao tác trên danh sách của mình để có được đầu ra mong muốn. Chúng ta hãy đi qua đoạn mã để hiểu rõ hơn về danh sách và các hoạt động của danh sách.

1. Tạo danh sách

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Đầu ra

['p', 'r', 'o', 'b', 'e']

2. Truy cập các mục từ Danh sách

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Đầu ra

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Thêm các mục mới vào danh sách

#adding item to the list
my_list + ['k']

Đầu ra

['p', 'r', 'o', 'b', 'e', 'k']

4. Loại bỏ các mục

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Đầu ra

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Đầu ra

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Danh sách sắp xếp

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Đầu ra

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Đầu ra

['y', 'r', 'm', 'l', 'k']

6. Tìm độ dài của một danh sách

#finding the length of list
 
len(my_list)

Đầu ra

5

TUPLE

Tuple rất giống với danh sách với một điểm khác biệt chính là tuple là NGAY LẬP TỨC , không giống như một danh sách. Khi chúng tôi tạo một bộ hoặc có một bộ, chúng tôi không được phép thay đổi các phần tử bên trong nó. Tuy nhiên, nếu chúng ta có một phần tử bên trong một tuple, chính là một danh sách, thì chỉ khi đó chúng ta mới có thể truy cập hoặc thay đổi trong danh sách đó. Để tạo một bộ giá trị, chúng ta phải viết các mục bên trong dấu ngoặc đơn . Giống như danh sách, chúng tôi có các phương pháp tương tự có thể được sử dụng với các bộ giá trị. Hãy xem qua một số đoạn mã để hiểu cách sử dụng bộ giá trị.

1. Tạo Tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Đầu ra

('apple', 'banana', 'guava')

2. Truy cập các mục từ Tuple

#accessing first element in tuple
 
my_tuple[1]

Đầu ra

'banana'

3. Chiều dài của một Tuple

#for finding the lenght of tuple
 
len(my_tuple)

Đầu ra

3

4. Chuyển đổi Tuple sang danh sách

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Đầu ra

list

5. Đảo ngược Tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Đầu ra

('guava', 'banana', 'apple')

6. Sắp xếp một Tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Đầu ra

('apple', 'banana', 'guava')

7. Xóa các phần tử khỏi Tuple

Để xóa các phần tử khỏi bộ tuple, trước tiên chúng tôi chuyển đổi bộ tuple thành một danh sách như chúng tôi đã làm trong một trong các phương pháp của chúng tôi ở trên (Điểm số 4), sau đó thực hiện theo cùng một quy trình của danh sách và loại bỏ rõ ràng toàn bộ bộ tuple, chỉ bằng cách sử dụng del tuyên bố .

TỪ ĐIỂN

Từ điển là một bộ sưu tập có nghĩa đơn giản là nó được sử dụng để lưu trữ một giá trị với một số khóa và trích xuất giá trị được cung cấp cho khóa. Chúng ta có thể coi nó như một tập hợp các cặp khóa: giá trị và mọi khóa trong từ điển được coi là duy nhất để chúng ta có thể truy cập các giá trị tương ứng tương ứng .

Một từ điển được biểu thị bằng cách sử dụng dấu ngoặc nhọn {} chứa các cặp key: value. Mỗi cặp trong từ điển được phân tách bằng dấu phẩy. Các phần tử trong từ điển không được sắp xếp theo thứ tự, trình tự không quan trọng khi chúng ta đang truy cập hoặc lưu trữ chúng.

Chúng MUTABLE có nghĩa là chúng ta có thể thêm, xóa hoặc cập nhật các phần tử trong từ điển. Dưới đây là một số ví dụ về mã để hiểu rõ hơn về từ điển trong python.

Một điểm quan trọng cần lưu ý là chúng ta không thể sử dụng một đối tượng có thể thay đổi làm khóa trong từ điển. Vì vậy, danh sách không được phép làm khóa trong từ điển.

1. Tạo từ điển

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Đầu ra

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Ở đây, số nguyên là khóa của từ điển và tên thành phố được kết hợp với số nguyên là giá trị của từ điển.

2. Truy cập các mục từ Từ điển

#access an item
 
print(my_dict[1])

Đầu ra

'Delhi'

3. Độ dài của từ điển

#length of the dictionary
 
len(my_dict)

Đầu ra

3

4. Sắp xếp từ điển

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Đầu ra

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Thêm các phần tử trong Từ điển

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Đầu ra

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Xóa các phần tử khỏi Từ điển

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Đầu ra

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

BỘ

Set là một kiểu dữ liệu khác trong python là một tập hợp không có thứ tự không có phần tử trùng lặp. Các trường hợp sử dụng phổ biến cho một tập hợp là loại bỏ các giá trị trùng lặp và thực hiện kiểm tra tư cách thành viên. Các dấu ngoặc nhọn hoặc set()hàm có thể được sử dụng để tạo bộ. Một điều cần lưu ý là trong khi tạo một tập hợp trống, chúng ta phải sử set()dụng. Sau đó tạo ra một từ điển trống. not { }

Dưới đây là một số ví dụ mã để hiểu rõ hơn về các bộ trong python.

1. Tạo một Tập hợp

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Đầu ra

{'apple', 'strawberry', 'mango'}

2. Truy cập các mục từ một Bộ

#to test for an element inside the set
 
"apple" in my_set

Đầu ra

True

3. Chiều dài của một bộ

print(len(my_set))

Đầu ra

3

4. Sắp xếp một tập hợp

print(sorted(my_set))

Đầu ra

['apple', 'mango', 'strawberry']

5. Thêm các phần tử trong Set

my_set.add("guava")
print(my_set)

Đầu ra

{'apple', 'guava', 'mango', 'strawberry'}

6. Xóa các phần tử khỏi Set

my_set.remove("mango")
print(my_set)

Đầu ra

{'apple', 'guava', 'strawberry'}

Sự kết luận

Trong bài viết này, chúng ta đã xem qua các cấu trúc dữ liệu được sử dụng phổ biến nhất trong python và cũng đã xem các phương thức khác nhau được liên kết với chúng.

Liên kết: https://www.askpython.com/python/data

#python #datastructures

August  Larson

August Larson

1662480600

The Most Commonly Used Data Structures in Python

In any programming language, we need to deal with data.  Now, one of the most fundamental things that we need to work with the data is to store, manage, and access it efficiently in an organized way so it can be utilized whenever required for our purposes. Data Structures are used to take care of all our needs.

What are Data Structures?

Data Structures are fundamental building blocks of a programming language. It aims to provide a systematic approach to fulfill all the requirements mentioned previously in the article. The data structures in Python are List, Tuple, Dictionary, and Set. They are regarded as implicit or built-in Data Structures in Python. We can use these data structures and apply numerous methods to them to manage, relate, manipulate and utilize our data.

We also have custom Data Structures that are user-defined namely Stack, Queue, Tree, Linked List, and Graph. They allow users to have full control over their functionality and use them for advanced programming purposes. However, we will be focussing on the built-in Data Structures for this article.

Implicit Data Structures Python

Implicit Data Structures Python

LIST

Lists help us to store our data sequentially with multiple data types. They are comparable to arrays with the exception that they can store different data types like strings and numbers at the same time. Every item or element in a list has an assigned index. Since Python uses 0-based indexing, the first element has an index of 0 and the counting goes on. The last element of a list starts with -1 which can be used to access the elements from the last to the first. To create a list we have to write the items inside the square brackets.

One of the most important things to remember about lists is that they are Mutable. This simply means that we can change an element in a list by accessing it directly as part of the assignment statement using the indexing operator.  We can also perform operations on our list to get desired output. Let’s go through the code to gain a better understanding of list and list operations.

1. Creating a List

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Output

['p', 'r', 'o', 'b', 'e']

2. Accessing items from the List

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Output

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Adding new items to the list

#adding item to the list
my_list + ['k']

Output

['p', 'r', 'o', 'b', 'e', 'k']

4. Removing Items

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Output

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Sorting List

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Output

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Output

['y', 'r', 'm', 'l', 'k']

6. Finding the length of a List

#finding the length of list
 
len(my_list)

Output

5

TUPLE

Tuples are very similar to lists with a key difference that a tuple is IMMUTABLE, unlike a list. Once we create a tuple or have a tuple, we are not allowed to change the elements inside it. However, if we have an element inside a tuple, which is a list itself, only then we can access or change within that list. To create a tuple, we have to write the items inside the parenthesis. Like the lists, we have similar methods which can be used with tuples. Let’s go through some code snippets to understand using tuples.

1. Creating a Tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Output

('apple', 'banana', 'guava')

2. Accessing items from a Tuple

#accessing first element in tuple
 
my_tuple[1]

Output

'banana'

3. Length of a Tuple

#for finding the lenght of tuple
 
len(my_tuple)

Output

3

4. Converting a Tuple to List

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Output

list

5. Reversing a Tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Output

('guava', 'banana', 'apple')

6. Sorting a Tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Output

('apple', 'banana', 'guava')

7. Removing elements from Tuple

For removing elements from the tuple, we first converted the tuple into a list as we did in one of our methods above( Point No. 4) then followed the same process of the list, and explicitly removed an entire tuple, just using the del statement.

DICTIONARY

Dictionary is a collection which simply means that it is used to store a value with some key and extract the value given the key. We can think of it as a set of key: value pairs and every key in a dictionary is supposed to be unique so that we can access the corresponding values accordingly.

A dictionary is denoted by the use of curly braces { } containing the key: value pairs. Each of the pairs in a dictionary is comma separated. The elements in a dictionary are un-ordered the sequence does not matter while we are accessing or storing them.

They are MUTABLE which means that we can add, delete or update elements in a dictionary. Here are some code examples to get a better understanding of a dictionary in python.

An important point to note is that we can’t use a mutable object as a key in the dictionary. So, a list is not allowed as a key in the dictionary.

1. Creating a Dictionary

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Here, integers are the keys of the dictionary and the city name associated with integers are the values of the dictionary.

2. Accessing items from a Dictionary

#access an item
 
print(my_dict[1])

Output

'Delhi'

3. Length of a Dictionary

#length of the dictionary
 
len(my_dict)

Output

3

4. Sorting a Dictionary

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Output

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Adding elements in Dictionary

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Removing elements from Dictionary

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

SET

Set is another data type in python which is an unordered collection with no duplicate elements. Common use cases for a set are to remove duplicate values and to perform membership testing. Curly braces or the set() function can be used to create sets. One thing to keep in mind is that while creating an empty set, we have to use set(), and not { }. The latter creates an empty dictionary.

Here are some code examples to get a better understanding of sets in python.

1. Creating a Set

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Output

{'apple', 'strawberry', 'mango'}

2. Accessing items from a Set

#to test for an element inside the set
 
"apple" in my_set

Output

True

3. Length of a Set

print(len(my_set))

Output

3

4. Sorting a Set

print(sorted(my_set))

Output

['apple', 'mango', 'strawberry']

5. Adding elements in Set

my_set.add("guava")
print(my_set)

Output

{'apple', 'guava', 'mango', 'strawberry'}

6. Removing elements from Set

my_set.remove("mango")
print(my_set)

Output

{'apple', 'guava', 'strawberry'}

Conclusion

In this article, we went through the most commonly used data structures in python and also saw various methods associated with them.

Link: https://www.askpython.com/python/data

#python #datastructures

Наиболее часто используемые структуры данных в Python

В любом языке программирования нам нужно иметь дело с данными. Теперь одной из самых фундаментальных вещей, которые нам нужны для работы с данными, является эффективное хранение, управление и доступ к ним организованным образом, чтобы их можно было использовать всякий раз, когда это необходимо для наших целей. Структуры данных используются для удовлетворения всех наших потребностей.

Что такое структуры данных?

Структуры данных являются фундаментальными строительными блоками языка программирования. Он направлен на обеспечение системного подхода для выполнения всех требований, упомянутых ранее в статье. Структуры данных в Python — это List, Tuple, Dictionary и Set . Они считаются неявными или встроенными структурами данных в Python . Мы можем использовать эти структуры данных и применять к ним многочисленные методы для управления, связывания, манипулирования и использования наших данных.

У нас также есть пользовательские структуры данных, определяемые пользователем, а именно Stack , Queue , Tree , Linked List и Graph . Они позволяют пользователям полностью контролировать их функциональность и использовать их для расширенных целей программирования. Однако в этой статье мы сосредоточимся на встроенных структурах данных.

Неявные структуры данных Python

Неявные структуры данных Python

СПИСОК

Списки помогают нам хранить наши данные последовательно с несколькими типами данных. Они сопоставимы с массивами за исключением того, что они могут одновременно хранить разные типы данных, такие как строки и числа. Каждый элемент или элемент в списке имеет назначенный индекс. Поскольку Python использует индексацию на основе 0, первый элемент имеет индекс 0, и подсчет продолжается. Последний элемент списка начинается с -1, что можно использовать для доступа к элементам от последнего к первому. Чтобы создать список, мы должны написать элементы внутри квадратных скобок .

Одна из самых важных вещей, которые нужно помнить о списках , это то, что они изменяемы . Это просто означает, что мы можем изменить элемент в списке, обратившись к нему напрямую как часть оператора присваивания с помощью оператора индексации. Мы также можем выполнять операции в нашем списке, чтобы получить желаемый результат. Давайте рассмотрим код, чтобы лучше понять список и операции со списками.

1. Создание списка

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Выход

['p', 'r', 'o', 'b', 'e']

2. Доступ к элементам из списка

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Выход

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Добавление новых элементов в список

#adding item to the list
my_list + ['k']

Выход

['p', 'r', 'o', 'b', 'e', 'k']

4. Удаление элементов

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Выход

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Выход

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Список сортировки

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Выход

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Выход

['y', 'r', 'm', 'l', 'k']

6. Нахождение длины списка

#finding the length of list
 
len(my_list)

Выход

5

КОРТЕЖ

Кортежи очень похожи на списки с той ключевой разницей, что кортеж является IMMUTABLE , в отличие от списка. Как только мы создаем кортеж или имеем кортеж, нам не разрешается изменять элементы внутри него. Однако если у нас есть элемент внутри кортежа, который сам является списком, только тогда мы можем получить доступ к этому списку или изменить его. Чтобы создать кортеж, мы должны написать элементы внутри круглых скобок . Как и со списками, у нас есть аналогичные методы, которые можно использовать с кортежами. Давайте рассмотрим некоторые фрагменты кода, чтобы понять, как использовать кортежи.

1. Создание кортежа

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Выход

('apple', 'banana', 'guava')

2. Доступ к элементам из кортежа

#accessing first element in tuple
 
my_tuple[1]

Выход

'banana'

3. Длина кортежа

#for finding the lenght of tuple
 
len(my_tuple)

Выход

3

4. Преобразование кортежа в список

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Выход

list

5. Реверс кортежа

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Выход

('guava', 'banana', 'apple')

6. Сортировка кортежа

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Выход

('apple', 'banana', 'guava')

7. Удаление элементов из кортежа

Для удаления элементов из кортежа мы сначала преобразовали кортеж в список, как мы сделали в одном из наших методов выше (пункт № 4), затем следовали тому же процессу списка и явно удалили весь кортеж, просто используя del заявление .

ТОЛКОВЫЙ СЛОВАРЬ

Словарь — это коллекция, которая просто означает, что она используется для хранения значения с некоторым ключом и извлечения значения по данному ключу. Мы можем думать об этом как о наборе пар ключ: значение, и каждый ключ в словаре должен быть уникальным , чтобы мы могли получить соответствующий доступ к соответствующим значениям .

Словарь обозначается фигурными скобками { } , содержащими пары ключ: значение. Каждая из пар в словаре разделена запятой. Элементы в словаре неупорядочены , последовательность не имеет значения, пока мы обращаемся к ним или сохраняем их.

Они ИЗМЕНЯЕМЫ , что означает, что мы можем добавлять, удалять или обновлять элементы в словаре. Вот несколько примеров кода, чтобы лучше понять словарь в Python.

Важно отметить, что мы не можем использовать изменяемый объект в качестве ключа в словаре. Таким образом, список не допускается в качестве ключа в словаре.

1. Создание словаря

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Здесь целые числа — это ключи словаря, а название города, связанное с целыми числами, — это значения словаря.

2. Доступ к элементам из словаря

#access an item
 
print(my_dict[1])

Выход

'Delhi'

3. Длина словаря

#length of the dictionary
 
len(my_dict)

Выход

3

4. Сортировка словаря

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Выход

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Добавление элементов в Словарь

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Удаление элементов из словаря

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

УСТАНОВЛЕН

Set — это еще один тип данных в python, представляющий собой неупорядоченную коллекцию без повторяющихся элементов. Общие варианты использования набора — удаление повторяющихся значений и проверка принадлежности. Фигурные скобки или set()функция могут использоваться для создания наборов. Следует иметь в виду, что при создании пустого набора мы должны использовать set(), и . Последний создает пустой словарь. not { }

Вот несколько примеров кода, чтобы лучше понять наборы в python.

1. Создание набора

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Выход

{'apple', 'strawberry', 'mango'}

2. Доступ к элементам из набора

#to test for an element inside the set
 
"apple" in my_set

Выход

True

3. Длина набора

print(len(my_set))

Выход

3

4. Сортировка набора

print(sorted(my_set))

Выход

['apple', 'mango', 'strawberry']

5. Добавление элементов в Set

my_set.add("guava")
print(my_set)

Выход

{'apple', 'guava', 'mango', 'strawberry'}

6. Удаление элементов из Set

my_set.remove("mango")
print(my_set)

Выход

{'apple', 'guava', 'strawberry'}

Вывод

В этой статье мы рассмотрели наиболее часто используемые структуры данных в Python, а также рассмотрели различные связанные с ними методы.

Ссылка: https://www.askpython.com/python/data

#python #datastructures

田辺  亮介

田辺 亮介

1662351030

Python中最常用的數據結構

在任何編程語言中,我們都需要處理數據。現在,我們需要處理數據的最基本的事情之一就是以有組織的方式有效地存儲、管理和訪問它,以便我們可以在需要時將其用於我們的目的。數據結構用於滿足我們所有的需求。

什麼是數據結構?

數據結構是編程語言的基本構建塊。它旨在提供一種系統的方法來滿足本文前面提到的所有要求。Python 中的數據結構是List、Tuple、Dictionary 和 Set。它們被視為Python 中的隱式或內置數據結構。我們可以使用這些數據結構並對它們應用多種方法來管理、關聯、操作和利用我們的數據。

我們還有用戶定義的自定義數據結構,即StackQueueTreeLinked ListGraph。它們允許用戶完全控制其功能並將其用於高級編程目的。但是,我們將專注於本文的內置數據結構。

隱式數據結構 Python

隱式數據結構 Python

列表

列表幫助我們以多種數據類型順序存儲數據。它們類似於數組,除了它們可以同時存儲不同的數據類型,如字符串和數字。列表中的每個項目或元素都有一個指定的索引。由於Python 使用基於 0 的索引,因此第一個元素的索引為 0,並且繼續計數。列表的最後一個元素以 -1 開頭,可用於訪問從最後一個到第一個的元素。要創建一個列表,我們必須將項目寫在方括號內

關於列表要記住的最重要的事情之一是它們是可變的。這僅僅意味著我們可以通過使用索引運算符直接訪問它作為賦值語句的一部分來更改列表中的元素。我們還可以對列表執行操作以獲得所需的輸出。讓我們通過代碼來更好地理解列表和列表操作。

1. 創建列表

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

輸出

['p', 'r', 'o', 'b', 'e']

2. 訪問列表中的項目

#accessing the list 
 
#accessing the first item of the list
my_list[0]

輸出

'p'
#accessing the third item of the list
my_list[2]
'o'

3. 向列表中添加新項目

#adding item to the list
my_list + ['k']

輸出

['p', 'r', 'o', 'b', 'e', 'k']

4. 移除物品

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

輸出

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

輸出

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5.排序列表

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

輸出

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

輸出

['y', 'r', 'm', 'l', 'k']

6. 查找列表的長度

#finding the length of list
 
len(my_list)

輸出

5

元組

元組與列表非常相似,關鍵區別在於元組是 IMMUTABLE,與列表不同。一旦我們創建了一個元組或有一個元組,我們就不能改變它裡面的元素。但是,如果我們在元組中有一個元素,它本身就是一個列表,那麼我們只能在該列表中訪問或更改。要創建一個元組,我們必須在括號內寫入項目。像列表一樣,我們有類似的方法可以用於元組。讓我們通過一些代碼片段來理解使用元組。

1. 創建一個元組

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

輸出

('apple', 'banana', 'guava')

2. 從元組訪問項目

#accessing first element in tuple
 
my_tuple[1]

輸出

'banana'

3. 元組的長度

#for finding the lenght of tuple
 
len(my_tuple)

輸出

3

4. 將元組轉換為列表

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

輸出

list

5. 反轉元組

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

輸出

('guava', 'banana', 'apple')

6. 對元組進行排序

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

輸出

('apple', 'banana', 'guava')

7. 從元組中刪除元素

為了從元組中刪除元素,我們首先將元組轉換為列表,就像我們在上面的方法之一(第 4 點)中所做的那樣,然後遵循列表的相同過程,並顯式刪除整個元組,只需使用del聲明

字典

字典是一個集合,它只是意味著它用於存儲帶有某個鍵的值並提取給定鍵的值。我們可以將其視為一組鍵:值對 和字典中的每個都應該是唯一的,以便我們可以相應地訪問相應的

字典由包含鍵:值對的花括號 { }表示。字典中的每一對都以逗號分隔。字典中的元素是無序的,當我們訪問或存儲它們時,序列並不重要。

它們是可變的,這意味著我們可以在字典中添加、刪除或更新元素。以下是一些代碼示例,可以更好地理解 python 中的字典。

需要注意的重要一點是,我們不能將可變對像用作字典中的鍵。因此,列表不允許作為字典中的鍵。

1. 創建字典

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

這裡,整數是字典的鍵,與整數相關的城市名稱是字典的值。

2. 從字典中訪問項目

#access an item
 
print(my_dict[1])

輸出

'Delhi'

3. 字典的長度

#length of the dictionary
 
len(my_dict)

輸出

3

4. 對字典進行排序

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

輸出

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. 在字典中添加元素

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6.從字典中刪除元素

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

Set 是 python 中的另一種數據類型,它是一個沒有重複元素的無序集合。集合的常見用例是刪除重複值並執行成員資格測試。花括號set()函數可用於創建集合。要記住的一件事是,在創建空集時,我們必須使用set(),。後者創建一個空字典。 not { }

以下是一些代碼示例,可幫助您更好地理解 Python 中的集合。

1. 創建一個 集合

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

輸出

{'apple', 'strawberry', 'mango'}

2. 訪問集合中的項目

#to test for an element inside the set
 
"apple" in my_set

輸出

True

3. 集合的長度

print(len(my_set))

輸出

3

4. 對集合進行排序

print(sorted(my_set))

輸出

['apple', 'mango', 'strawberry']

5. 在Set中添加元素

my_set.add("guava")
print(my_set)

輸出

{'apple', 'guava', 'mango', 'strawberry'}

6. 從 Set 中移除元素

my_set.remove("mango")
print(my_set)

輸出

{'apple', 'guava', 'strawberry'}

結論

在本文中,我們瀏覽了 Python 中最常用的數據結構,並了解了與它們相關的各種方法。

鏈接:https ://www.askpython.com/python/data

#python #datastructures