2020/python (codecademy)

Working with Lists in Python

bNayC 2020. 4. 15. 03:47

Length of a List

Often, we’ll need to find the number of items in a list, usually called its length.

We can do this using the function len. When we apply len to a list, we get the number of elements in that list:

와잇 
답) 이렇게 막 엮는거 더 연습 필요하다.

 

Selecting List Elements I

calls = ['Ali', 'Bob', 'Cam', 'Doug', 'Ellie']

First, he’ll call 'Ali', then 'Bob', etc.

In Python, we call the order of an element in a list its index.

 

Python lists are zero-indexed. This means that the first element in a list has index 0, rather than 1

 

와잇

 

Selecting List Elements II

What if we want to select the last element of a list?

We can use the index -1 to select the last item of a list, even when we don’t know how many elements are in a list

 

와잇

 

Slicing Lists

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

 

Suppose we want to select from b through f.

We can do this using the following syntax: letters[start:end], where:

  • start is the index of the first element that we want to include in our selection. In this case, we want to start at b, which has index 1.
  • end is the index of one more than the last index that we want to include. The last element we want is f, which has index 5, so end needs to be 6.

sublist = letters[1:6]

print(sublist)

 

 

Slicing Lists II

위에 예시에서 3이 아니라 4 아닌가 

 

익숙해지깃!
와잇
답 (아... suitecase에서 가지고 오는거였구낭... 기초...가 .....)

Counting elements in a list

ex) If we want to know how many times i appears in this word, we can use the function count:

 

Sorting Lists I

Sometimes, we want to sort a list in either numerical (1, 2, 3, …) or alphabetical (a, b, c, …) order.

We can sort a list in place using .sort(). Suppose that we have a list of names:

 

왜 에러가 뜨는거닝
와잇

Sorting Lists II

A second way of sorting a list is to use sorted. sorted is different from .sort() in several ways:

  1. It comes before a list, instead of after.
  2. It generates a new list.

questions