3-1-2-22. Lists and Membership Operators

which contain other datatypes and even other containers.

So, let’s introduce our first Python container: lists.

A list is a data structure in Python that is a mutable ordered sequence of elements.

More on the mutable ordered part later.

This code defines a variable months,

which contains a list of strings.

Each element in the list is a month of the year.

A list is defined using square brackets and

always holds other data which are separated by commas.

This data could be a mix of any of the datatypes you’ve already seen.

Lists have an order,

or more appropriately, are ordered.

We can look up individual elements in the list by their index.

We can look up values in a list like this.

We type in the list name,

followed by square brackets,

with an integer indicating its position or index.

Notice that the first element in the list, January,

is located at index zero rather than index one.

Many programming languages follow this convention called zero-based indexing.

If zero-based indexing is confusing,

consider it this way.

An element’s index describes how far the element is from the beginning of the list.

The first element is zero elements away from the beginning.

The second one is one element away and so on.

We can also index from the end of the list,

rather than the front,

like we’ve been doing so far.

To do this, we use negative indices.

For example, we can get the last month of the year.

The index negative one refers to the last element of the list,

negative two to the second to last, and so on.

Note that while zero is the first index of the list,

negative zero is not the last,

which can be a bit confusing.

If you attempt to access an index in a list that does not exist,

you will get a list index exception.

This is Python’s way of telling you that you are trying

to access an index that is not in the list.

Since the index 25 does not exist,

we receive this error.

Getting index errors is quite common,

especially if you’re not used to indexing in Python.

You might get these errors quite a lot in the beginning.

The most common reason for getting an index error is using an index that’s off by one,

but there may be other reasons why you would get such an error.

It is always a good idea to use the print function and debug with the small example.

This can tell you if your indexing is off and by how much.

약간 혼란 스러울 수 있습니다.

존재하지 않는 목록의 인덱스에 액세스하려고 하면,

목록 색인 예외가 발생합니다.

이것은 당신이 시도하고 있다고 말하는 Python의 방법입니다.

목록에 없는 인덱스에 액세스합니다.

인덱스 25가 존재하지 않기 때문에,

이 오류가 발생합니다.

인덱스 오류가 발생하는 것은 매우 일반적입니다.

특히 Python에서 인덱싱에 익숙하지 않은 경우.

처음에는 이러한 오류가 많이 발생할 수 있습니다.

인덱스 오류가 발생하는 가장 일반적인 이유는 1만큼 벗어난 인덱스를 사용하기 때문입니다.

그러나 그러한 오류가 발생하는 다른 이유가 있을 수 있습니다.

작은 예제로 인쇄 기능을 사용하고 디버그하는 것은 항상 좋은 생각입니다.

이것은 인덱싱이 꺼져 있는지 여부와 그 정도를 알려줄 수 있습니다.

We will see more data types that fall under

different sections of this grid as we continue.

For now, we’ll explore the methods and functions that work on lists.

And we’ll take advantage of lists mutability in our programs.

그렇다면 목록은 문자열과 어떻게 다른가요?

둘 다 인덱싱을 지원한다는 것을 알았습니다.

슬라이싱 및 in 연산자.

가장 눈에 띄는 차이점은,

문자열은 일련의 문자인 반면 목록 요소는 모든 유형의 객체가 될 수 있습니다.

또는 더 미묘한 차이점은 목록은 수정할 수 있지만 문자열은 수정할 수 없다는 것입니다.

여기서 원하는 경우 이 목록의 네 번째 요소 인덱스 3을 Friday로 변경할 수 있습니다.

그러나 여기서 문자열의 세 번째 요소를 변경하려고 하면 오류가 발생합니다.

객체가 될 수 있는지 여부에 대한 기술 용어

생성 후 수정된 것은 가변성입니다.

목록의 값을 수정할 수 있습니다.

따라서 목록은 변경할 수 없는 데이터 유형입니다.

문자열을 수정할 수 없습니다.

따라서 문자열은 변경할 수 없는 데이터 유형입니다.

더 많은 데이터 유형을 도입함에 따라 계속해서 고려할 두 가지 요소가 있습니다.

하나는 가변성이고 다른 하나는 순서입니다.

순서는 객체에 대한 내용의 순서가 중요한지 여부입니다.

및 이 순서를 사용하여 개체의 경로에 액세스할 수 있는지 여부.

문자열과 목록 모두 순서가 지정됩니다.

이것이 인덱싱이 잘 작동하는 이유입니다.

그러나 하나는 변경 가능하지만 다른 하나는 변경 불가능합니다.

다음에 해당하는 더 많은 데이터 유형을 보게 될 것입니다.

계속 진행하면서 이 그리드의 다른 섹션을 참조하세요.

지금은 목록에서 작동하는 메서드와 함수를 살펴보겠습니다.

그리고 우리는 프로그램에서 목록 변경 가능성을 이용할 것입니다.


Data structures are containers that organize and group data types together in different ways. A list is one of the most common and basic data structures in Python.

You saw here that you can create a list with square brackets. Lists can contain any mix and match of the data types you have seen so far.

list_of_random_things = [1, 3.4, 'a string', True]

This is a list of 4 elements. All ordered containers (like lists) are indexed in python using a starting index of 0. Therefore, to pull the first value from the above list, we can write:

>>> list_of_random_things[0]

It might seem like you can pull the last element with the following code, but this actually won’t work:

>>> list_of_random_things[len(list_of_random_things)] 
IndexError                                Traceback (most recent call last)
<ipython-input-34-f88b03e5c60e> in <module>()
----> 1 lst[len(lst)]

IndexError: list index out of range

However, you can retrieve the last element by reducing the index by 1. Therefore, you can do the following:

>>> list_of_random_things[len(list_of_random_things) - 1] 

Alternatively, you can index from the end of a list by using negative values, where -1 is the last element, -2 is the second to last element and so on.

>>> list_of_random_things[-1] 
>>> list_of_random_things[-2] 
a string

Slice and Dice with Lists

You saw that we can pull more than one value from a list at a time by using slicing. When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

Therefore, this:

>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]

will only return 3.4 in a list. Notice this is still different than just indexing a single element, because you get a list back with this indexing. The colon tells us to go from the starting value on the left of the colon up to, but not including, the element on the right.

If you know that you want to start at the beginning, of the list you can also leave out this value.

>>> list_of_random_things[:2]
[1, 3.4]

or to return all of the elements to the end of the list, we can leave off a final element.

>>> list_of_random_things[1:]
[3.4, 'a string', True]

This type of indexing works exactly the same on strings, where the returned value will be a string.

Are you in OR not in?

You saw that we can also use in and not in to return a bool of whether an element exists within our list, or if one string is a substring of another.

>>> 'this' in 'this is a string'
>>> 'in' in 'this is a string'
>>> 'isa' in 'this is a string'
>>> 5 not in [1, 2, 3, 4, 6]
>>> 5 in [1, 2, 3, 4, 6]

Mutability and Order

Mutability is about whether or not we can change an object once it has been created. If an object (like a list or string) can be changed (like a list can), then it is called mutable. However, if an object cannot be changed without creating a completely new object (like strings), then the object is considered immutable.

>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]

As shown above, you are able to replace 1 with ‘one’ in the above list. This is because lists are mutable.

However, the following does not work:

>>> greeting = "Hello there"
>>> greeting[0] = 'M'

This is because strings are immutable. This means to change this string, you will need to create a completely new string.

There are two things to keep in mind for each of the data types you are using:

  1. Are they mutable?
  2. Are they ordered?

Order is about whether the position of an element in the object can be used to access the element. Both strings and lists are ordered. We can use the order to access parts of a list and string.

However, you will see some data types in the next sections that will be unordered. For each of the upcoming data structures you see, it is useful to understand how you index, are they mutable, and are they ordered. Knowing this about the data structure is really useful!

Additionally, you will see how these each have different methods, so why you would use one data structure vs. another is largely dependent on these properties, and what you can easily do with it!

%d 블로거가 이것을 좋아합니다: